Unexpected behavior with loop macro and closures

前端 未结 2 1342
星月不相逢
星月不相逢 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:13

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题