In LISP how to inspect free variables in a closure?

这一生的挚爱 提交于 2019-12-08 21:24:18

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6165836/in-lisp-how-to-inspect-free-variables-in-a-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!