在 LISP 中如何检查闭包中的自由变量?
在 lisp 中,我可以像这样绑定在闭包中绑定的自由变量...
(let ((x 1) (y 2) (z 3))
(defun free-variables () (+ x y z)))
(free-variables)
结果...
6
我想知道是否可以动态检查绑定的闭包变量?
例如
(inspect-closure free-variables)
导致类似...
((x 1) (y 2) (z 3))
谢谢
In lisp I can bind free variables bound in a closure like this...
(let ((x 1) (y 2) (z 3))
(defun free-variables () (+ x y z)))
(free-variables)
results in ...
6
What I want to know is if it is possible to inspect bound closure variables dynamically?
E.g.
(inspect-closure free-variables)
resulting in something like...
((x 1) (y 2) (z 3))
Thanks SO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Common Lisp
只能从同一范围内的函数访问闭包的内部变量(参见 Jeff 的回答)。即使那些也无法在某个地方查询这些变量。 Common Lisp 标准不提供此功能。
显然,在许多情况下,各个 Common Lisp 实现都知道如何获取此信息。例如,如果您查看 GNU Emacs 的 SLIME 代码(一种 Common Lisp 开发环境),inspect 和 backtrace 功能的代码应该提供这一点。开发希望向用户/程序员展示这一点,Common Lisp 标准不提供该信息。
Common Lisp
Access to the closure's internal variables is only possible from functions in the same scope (See Jeff's answer). Even those can't query somewhere for these variables. This functionality is not provided by the Common Lisp standard.
Obviously in many cases individual Common Lisp implementations know how to get this information. If you look for example at the SLIME code (a Common Lisp development environment) for GNU Emacs, the code for inspect and backtrace functionalities should provide that. The development wants to show this - for the user/programmer the Common Lisp standard does not provide that information.
您可以在一个封装内拥有多个函数,因此只需添加另一个函数
并将其放入您的
let
语句中。如果您尝试创建一个将访问 -any- 闭包的函数,那么严格来说,我不认为这是可能的。 x、y 和 z 是本地定义的,因此如果你想向全世界宣布它们,它必须来自闭包内部。您可以做的是构建一个重复
let
功能的宏,并添加返回其局部变量的功能。您可能想将其命名为不同的名称,例如mylet
或其他名称。You can have multiple functions inside an enclosure, so just add another function
and put it inside your
let
statementIf you're trying to create a function that will access -any- closure then, strictly speaking, I don't think it's possible. x, y, and z are defined locally so if you want to announce them to the world it has to come from within the closure. What you COULD do is build a macro that duplicates
let
functionality with the added ability to return its local variables. You'll probably want to name it something different, likemylet
or whatever.