Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LISP is it possible to access a function's form?

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?

like image 263
Reuben Peter-Paul Avatar asked Apr 30 '11 21:04

Reuben Peter-Paul


People also ask

What are the basic functions of LISP?

A function is a set of statements that takes some input, performs some tasks, and produces the result. Through functions, we can split up a huge task into many smaller functions. They also help in avoiding the repetition of code as we can call the same function for different inputs.

Which command is used to define a function in Lisp?

The defun construct is used for defining a function, we will look into it in the Functions chapter. Create a new source code file named main. lisp and type the following code in it. When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.

What is the use of Zerop in Lisp?

Description: Returns true if number is zero (integer, float, or complex); otherwise, returns false. Regardless of whether an implementation provides distinct representations for positive and negative floating-point zeros, (zerop -0.0) always returns true. Side Effects: None.


1 Answers

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.

like image 182
danlei Avatar answered Sep 17 '22 18:09

danlei