开发者

In LISP how to inspect free variables in a closure?

开发者 https://www.devze.com 2023-03-09 05:01 出处:网络
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)))

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 i开发者_运维百科n something like...

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

Thanks SO


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号