问题
Suppose I define a function globally:
(defun x (y) (1+ y)) ;; Edit: my first example was too complicated
Is it possible to "coerce" the function x into a list like:
(x (y) (1+ y))
Thanks in advance!
PS - @Danlei's example works in Clozure CL with a special flag, however does anyone know how to get FUNCTION-LAMBDA-EXPRESSION to work in SBCL?
回答1:
You could try FUNCTION-LAMBDA-EXPRESSION:
(function-lambda-expression #'foo)
But it's not guaranteed to work ("… implementations are free to return ``nil, true, nil'' in all cases …").
For example in CCL:
CL-USER> (setq ccl:*save-definitions* t)
T
CL-USER> (defun x (x y) (+ x y))
X
CL-USER> (function-lambda-expression #'x)
(LAMBDA (X Y) (DECLARE (CCL::GLOBAL-FUNCTION-NAME X)) (BLOCK X (+ X Y)))
NIL
X
In SBCL, you might try (setq sb-ext:*evaluator-mode* :interpret)
(untested). Maybe there are other ways to achieve this in SBCL (you might look for an analog of *save-definitions*
or even try different OPTIMIZE
settings), but I don't know about them. Beware that functions entered in the REPL won't be compiled after setting *evaluator-mode*
to :interpret
, so you will probably experience worse performance.
回答2:
In Common Lisp, you might be able to recover the definition of a function using function-lambda-expression
(see the HyperSpec) or in some implementations uncompile-function
.
回答3:
When I was spending time on a project to do significant function manipulation, it was easiest to do this sort of thing:
(defclass node ()
(list-form
compiled-obj))
First the list form consisting of '(lambda foo (x ) bar) would be assigned, then I would compile Foo and assign it to the compiled-ojb slot.
来源:https://stackoverflow.com/questions/5844670/in-lisp-is-it-possible-to-access-a-functions-form