Next: , Up: Macros   [Contents][Index]


5.10.1 Defining Macros

Macros are defined in the same style as functions, the only difference is the name of the special form used to define them.

A macro object is a list whose car is the symbol macro, its cdr is the function which creates the expansion of the macro when applied to the macro calls unevaluated arguments.

Macro: defmacro name lambda-list body-forms…

Defines the macro stored in the function cell of the symbol name. lambda-list is the lambda-list specifying the arguments to the macro (see Lambda Expressions) and body-forms are the forms evaluated when the macro is expanded. The first of body-forms may be a documentation string describing the macro’s use.

Here is a simple macro definition, it is the definition of the when macro shown in the previous section.

(defmacro when (condition #!rest body)
  "Evaluates condition, if it's true evaluates the body
forms."
  (list 'cond (list* condition body)))

When a form of the type (when c b …) is evaluated the macro definition of when expands to the form (cond (c (progn b …))) which is then evaluated to perform the when-construct.

When you define a macro ensure that the forms which produce the expansion have no side effects; otherwise undefined effects will occur when programs using the macro are compiled.