Whoa! Do Python and Lisp really have LAMBDA ?

Bradd W. Szonye bradd+news at szonye.com.invalid
Sun Oct 26 04:51:56 EST 2003


> (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).

Yes, that is suprising, although it makes more sense once you realize
that they all bind to the same i, which is mutated during the loop.

> I'm sure Haskell does this right. What about Scheme and ML?

The equivalent in Scheme (named let) introduces a new binding with each
iteration, so it does what you expect.

    (define flist
      (let loop ((i 0) (r '()))
        (cond ((> i 2) (reverse r))
               (else (loop (+ 1 i)
                           (cons (lambda (x) (+ x i)) r))))))

    (let loop ((l flist) (r '()))
      (cond ((null? l) (reverse r))
             (else (loop (cdr l)
                         (cons ((car l) 1) r)))))

Unlike the Lisp version of flist, the Scheme loop binds a new i for each
iteration. Therefore, each closure has its own i.

My Scheme version is much wordier than the Lisp version above. Perhaps
the more experienced schemers can show you a less verbose version that
still does what you want. I've always been fond of functional languages,
but I've only recently had the chance to work with them extensively, so
I'm still learning.
-- 
Bradd W. Szonye
http://www.szonye.com/bradd
My Usenet e-mail address is temporarily disabled.
Please visit my website to obtain an alternate address.




More information about the Python-list mailing list