Of what use is 'lambda'???

Erik Max Francis max at alcyone.com
Sun Sep 24 20:53:43 CEST 2000

Jonadab the Unsightly One wrote:

> But I have
> yet to be made to understand how it harms a function to
> be bound to a symbol.  Functions *like* being bound to
> symbols.  It gives them a nice home, where you can always
> find them -- which improves code reusability.

It doesn't "harm" them, but it sometimes makes things simpler.  Often a
module or library will have internal functions that the user _shouldn't_
call.  Using lambdas on the fly for these kind of applications
eliminates the need to hide symbols from the user, because they never
had symbols to begin with.

> I will,
> however, admit that I haven't messed with mapcar enough
> to say for sure that I wouldn't want lambda for that.

This is probably the main application of lambdas; it's a case where you
need a throwaway function to use as glue but it doesn't need a symbol
and you probably won't use it again.

So in LISP (Python example follows) let's say that we're going along on
our way to accomplishing some task and find that as a quick step in a
calculation we have to transform a list of integers into a list of the
squares of those integers.  (This is contrived example, but this kind of
thing happens all the time.)  Say your list is l:

    (setq l '(1 2 3 4 5 6))

and you want to turn that use mapcar to square this.  First you'd need
to define a square function:

    (defun square (x) (* x x)) ; takes x -> x*x

Then to apply this list with mapcar you'd do

    (mapcar 'square l)

which evaluates to (1 4 9 16 25 36), a list of squares of our original

But if this is a throwaway statement, defining the function takes extra
steps.  With mapcar and lambda, we could just write this as:

    (mapcar '(lambda (x) (* x x)) l) ; or #' to deal with free symbols

which gives the same result, and doesn't clutter up the symbol space
with a symbol for a function we don't need, and puts everything
relatively easy to read line.

In Python you have the same situation, although the equivalent of mapcar
in Python is map:

    l = [1, 2, 3, 4, 5, 6]
    def square(x):
        return x*x
    lSquared = map(square, l)

You can avoid the unnecessary function definition by using a lambda:

    lSquared = map(lambda x: x*x, l)

 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Take my advice:  Pull down your pants and slide on the ice.
\__/ Dr. Sidney Freedman
    Official Buh rules / http://www.alcyone.com/max/projects/cards/buh/
 The official rules to the betting card game, Buh.

More information about the Python-list mailing list