Whoa! Do Python and Lisp really have LAMBDA ?

Marco Antoniotti marcoxa at cs.nyu.edu
Mon Oct 27 10:28:55 EST 2003



mike420 at ziplip.com wrote:
> Earlier Ed Schofield (thanks, man) warned us that
> 
> flist = []
> 
> for i in range(3)
>     f = lambda x: x + i
>     flist.append(f)
> 
> [f(1) for f in flist]
> 
> gives [3, 3, 3]. So much for the principle of minimum surprise!
> 
> Doing the same in Lisp (with lists instead of arrays),
> 
> (setf flist (loop for i from 0 to 2 
>                   collect (lambda (x) (+ x i))))
> 
> (loop for f in flist 
>       collect (funcall f 1))
> 
> I got (4 4 4).
> 
> Lisp has many gotchas, I just wasn't ready for this one.
> (Google for "lisp gotchas" - someone posted a comprehensive
> list to c.l.l. in 1995. Every Lisper should read it)
> 
> I'm sure Haskell does this right. What about Scheme and ML?

Common Lisp does it right.

(mapcar (lambda (f) (funcall f 1))
    (mapcar (lambda (i)
               (lambda (x) (+ x i)))
       (list 1 2 3)))

... This is what the Haskell code eventually boild down to.

It is Python that apparently cannot do this.  But, in all fairness, 
nowhere in Python there is a claim that lambda expressions are full fledged.

The LOOP based version of Common Lisp does not do what you think it does 
because the LOOP semantics is not the one you think it is.

Of course, I can always come up with a nice set of macros that would 
hide some of the syntactic messiness in CL (of course do not ask me to 
change the evaluation rules for CL: CL is simply not lazy)

Cheers
--
Marco







More information about the Python-list mailing list