小编sha*_*ica的帖子

Common Lisp (SBCL) 中的动态变量闭包

我了解此代码的工作原理:

(defvar *nums* '(2 3 5))

(defun print-nums ()
  (format t "~a~%" *nums*))

(print-nums)
-> (2 3 5)
-> NIL
Run Code Online (Sandbox Code Playgroud)

我什至明白动态绑定变量的新值是如何在这段代码中*nums*传递的print-nums

(let ((*nums* '(1 2 3)))
  (print-nums))
-> (1 2 3)
-> NIL
Run Code Online (Sandbox Code Playgroud)

但是为什么下面的代码不能以同样的方式工作?

(defvar *my-nums-f* (let ((*nums* '(1 2 3)))
                      #'(lambda () (format t "~a~%" *nums*))))

(funcall *my-nums-f*)
-> (2 3 5)
-> NIL
Run Code Online (Sandbox Code Playgroud)

闭包的概念是否不适用于动态绑定变量,还是我做错了什么?如果我错误地理解了闭包的概念,有人可以向我解释一下吗?

lisp scope sbcl common-lisp

3
推荐指数
1
解决办法
320
查看次数

标签 统计

common-lisp ×1

lisp ×1

sbcl ×1

scope ×1