Macro definitions are similar to function definitions, but there are some crucial differences. A macro is a piece of code that creates another lisp object for evaluation. This process is called ``macro expansion''. Macro expansion happens before any arguments are evaluated.
Here is an example of a macro definition:
> (defmacro 2plus (x) (+ x 2)) 2PLUS > (setf a 3) ;; setf is a macro too! 3 > (2plus a) 5In this example the form "(+ x 2)" gets expanded to "(+ a 2)" before a is evaluated.
Because expansion occurs prior to evaluation, arguments passed to a macro will not necessarily be evaluated. This result is that macros behave rather differently from functions. For example:
> (defmacro just-first-macro (x y) x) JUST-FIRST-MACRO > (just-first-macro 3 4) 3 > (just-first-macro 3 (print 4)) 3 ;; (print 4) is not evaluated > (defun just-first-function (x y) x) JUST-FIRST-FUNCTION > (just-first-function 3 (print 4)) 4 ;; (print 4) is evaluated 3
Many macros are built in to Lisp. For example (in addition to setf) cond, if, and, and or are all macros.
Because macros do not evaluate all their arguments, they can result in
more efficient code.
© Colin Allen & Maneesh Dhagat