Go to the first, previous, next, last section, table of contents.


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.

Special Form: 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 section 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 a possible definition for the when construct (which might even be useful if when wasn't already defined as a special form...),

(defmacro when (condition &rest body)
  "Evaluates condition, if it's non-nil evaluates the body
forms."
  (list 'if condition (cons 'progn body)))

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

When you define a macro ensure that the forms which produce the expansion have no side effects; it would fail spectacularly when you attempt to compile your program!


Go to the first, previous, next, last section, table of contents.