Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LISP how to inspect free variables in a closure?

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

like image 332
Reuben Peter-Paul Avatar asked May 29 '11 03:05

Reuben Peter-Paul


2 Answers

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.

like image 74
Rainer Joswig Avatar answered Nov 17 '22 23:11

Rainer Joswig


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.

like image 27
Jeff Avatar answered Nov 17 '22 22:11

Jeff