methusala wrote:Hello, My nick is Methusala and I am a recovering Javaholic.
We're here for ya, buddy!
how do you use a function like a list?
You don't. You define a macro that returns a function call* as a list, and then you call the macro. (see below)
- Code: Select all
CL-USER> (defun h (x) (+ x x))
H
CL-USER> (h 2)
4
CL-USER> (symbol-function 'h)
#<CLOSURE H (X) (DECLARE (SYSTEM::IN-DEFUN H)) (BLOCK H (+ X X))>
CL-USER> (car (symbol-function 'h))
Why do you want to do that? The function may be compiled, in which case it won't be a list.
What should I use instead of symbol-function to get the above to return the car of a list?
What are you trying to do? If you just want to explore that whole code-is-data thing, then what you want is a macro that encapsulates a piece of code. The macro returns a list that represents a function call*, and the call is automatically evaluated.
So for example, suppose you want to define synonyms for binary functions. This can do it:
- Code: Select all
(defmacro defop (name op) `(defun ,name (x y) (,op x y)))
DEFOP will return a list that contains a call to DEFUN. The backquote notation is common in macro definitions. It's equivalent to this:
- Code: Select all
(list 'defun name '(x y) (list op 'x 'y))
The list returned by the backquote is the return value of the macro DEFOP. Use MACROEXPAND-1 to see the list:
- Code: Select all
CL-USER> (macroexpand-1 '(defop plus +))
(DEFUN PLUS (X Y) (+ X Y))
When you call DEFOP, the list is automatically evaluated:
- Code: Select all
CL-USER> (defop plus +)
PLUS
CL-USER> (plus 1 2)
3
*or a call to another macro or a special operation.