6

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

Drew
  • 29,895
  • 7
  • 74
  • 104
Reuben Peter-Paul
  • 1,550
  • 3
  • 15
  • 25

2 Answers2

7

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.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
4

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.

Jeff
  • 12,147
  • 10
  • 51
  • 87
  • 1
    Thanks Jeff, but I'm looking for programmatic access to enclosed variables like a listing- or inspection-style type function. Apparently it is not supported in standard CL. – Reuben Peter-Paul May 30 '11 at 12:58
  • 1
    Then I think, as per the second part of my answer, your best bet is to create a macro. Sorry we couldn't be of more help! – Jeff May 30 '11 at 14:22