next up previous
Contents Next: Appendix: Selected Lisp Up: FunctionsLambda Expressions, Previous: Backquote and Commas

Defmacro

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
> (2plus 3)
5
> (setf a (2plus 3))   ;; setf is a macro too!
5

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.

Macros are usually used to simplify or extend the syntax of the language. Because macros do not evaluate all their arguments, they can sometimes result in more efficient code.


© Colin Allen & Maneesh Dhagat
May 1999