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

发布于 2024-11-10 00:42:52 字数 360 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

惟欲睡 2024-11-17 00:42:52

Common Lisp

只能从同一范围内的函数访问闭包的内部变量(参见 Jeff 的回答)。即使那些也无法在某个地方查询这些变量。 Common Lisp 标准不提供此功能。

显然,在许多情况下,各个 Common Lisp 实现都知道如何获取此信息。例如,如果您查看 GNU Emacs 的 SLIME 代码(一种 Common Lisp 开发环境),inspectbacktrace 功能的代码应该提供这一点。开发希望向用户/程序员展示这一点,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.

格子衫的從容 2024-11-17 00:42:52

您可以在一个封装内拥有多个函数,因此只需添加另一个函数

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

并将其放入您的 let 语句中。

如果您尝试创建一个将访问 -any- 闭包的函数,那么严格来说,我不认为这是可能的。 x、y 和 z 是本地定义的,因此如果你想向全世界宣布它们,它必须来自闭包内部。您可以做的是构建一个重复 let 功能的宏,并添加返回其局部变量的功能。您可能想将其命名为不同的名称,例如 mylet 或其他名称。

You can have multiple functions inside an enclosure, so just add another function

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

and put it inside your let statement

If 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, like mylet or whatever.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文