简体   繁体   English

在 LISP 中如何检查闭包中的自由变量?

[英]In LISP how to inspect free variables in a closure?

In lisp I can bind free variables bound in a closure like this...在 lisp 中,我可以像这样绑定绑定在闭包中的自由变量...

(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?我想知道的是是否可以动态检查绑定的闭包变量?

Eg例如

(inspect-closure free-variables)

resulting in something like...导致类似...

((x 1) (y 2) (z 3))

Thanks SO谢谢所以

Common Lisp通用 Lisp

Access to the closure's internal variables is only possible from functions in the same scope (See Jeff's answer).只能从同一个 scope 中的函数访问闭包的内部变量(参见 Jeff 的回答)。 Even those can't query somewhere for these variables.即使是那些也无法在某处查询这些变量。 This functionality is not provided by the Common Lisp standard. Common Lisp 标准不提供此功能。

Obviously in many cases individual Common Lisp implementations know how to get this information.显然,在许多情况下,单独的 Common Lisp 实现知道如何获取这些信息。 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.例如,如果您查看 GNU Emacs 的 SLIME 代码(Common Lisp 开发环境),则检查回溯功能的代码应该提供该代码。 The development wants to show this - for the user/programmer the Common Lisp standard does not provide that information.开发人员希望展示这一点——对于用户/程序员,Common Lisp 标准不提供该信息。

You can have multiple functions inside an enclosure, so just add another function您可以在外壳内拥有多种功能,因此只需添加另一个 function

(defun inspect-closure () (list (list 'x x) (list 'y y) (list 'z z)))

and put it inside your let statement并将其放在您的let语句中

If you're trying to create a function that will access -any- closure then, strictly speaking, I don't think it's possible.如果您尝试创建一个可以访问 -any- 闭包的 function,那么严格来说,我认为这是不可能的。 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. x、y 和 z 是在本地定义的,所以如果你想向世界宣布它们,它必须来自闭包内。 What you COULD do is build a macro that duplicates let functionality with the added ability to return its local variables.您可以做的是构建一个复制let功能的宏,并增加了返回其局部变量的能力。 You'll probably want to name it something different, like mylet or whatever.你可能想给它起个不同的名字,比如mylet类的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM