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


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))
> (setf a 3)   ;; setf is a macro too!
> (2plus a)
In 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 3 4)
> (just-first-macro 3 (print 4))
3                     ;; (print 4) is not evaluated
> (defun just-first-function (x y) x)
> (just-first-function 3 (print 4))
4                     ;; (print 4) is evaluated

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
May 1999