<mike420@ziplip.com> wrote:
+---------------
| 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.
+---------------
Why should this be considered a "gotcha"? It's doing exactly what
you asked it to: all three lambdas are closed over the *same* variable
binding, which was left holding "3" when the loop finished. Try it
this way instead and you might get what you wanted/expected:
> (defparameter flist (loop for i from 0 to 2
collect (let ((u i))
(lambda (x) (+ x u)))))
FLIST
> (loop for f in flist
collect (funcall f 1))
(1 2 3)
>
In this case the lambdas are closed over *distinct* bindings.
-Rob
-----
Rob Warnock <rpw3@rpw3.org>
627 26th Avenue <URL:http://rpw3.org/>
San Mateo, CA 94403 (650)572-2607