Why do these forms behave this way?
CL-USER>
(setf *closures*
(loop for num in (list 1 2 3 4)
collect (lambda ()
n
The name num
represents the same binding during the evaluation of LOOP.
Maybe you want to write:
(mapcar 'constantly (list 1 2 3 4))
to get what you meant.
num
is same variable shared by all lambdas.
Use
(setf *closures*
(loop for num in (list 1 2 3 4)
collect (let ((num1 num))
(lambda ()
num1))))
num1
is fresh variable for each iteration.
As of dolist
, "It is implementation-dependent whether dolist establishes a new binding of var on each iteration or whether it establishes a binding for var once at the beginning and then assigns it on any subsequent iterations." (CLHS, Macro DOLIST). So it may work on one implementation and fail on other.