Unexpected behavior with loop macro and closures

前端 未结 2 1345
星月不相逢
星月不相逢 2020-12-18 10:49

Why do these forms behave this way?

CL-USER>
(setf *closures*
      (loop for num in (list 1 2 3 4)
            collect (lambda ()
                      n         


        
2条回答
  •  北海茫月
    2020-12-18 11:17

    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.

提交回复
热议问题