Lisp/Macros

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

DEFMACRO

(defmacro name (parameters)
  "documentation"
  body)

Defines a macro. Note that the parameters are usually lists ready to be evaluated.

Cautions:

  1. Be sure to execute the expressions left-to-right, unless it obviously shouldn't be done that way.
  2. Be sure to execute the expressions exactly once, unless it obviously shouldn't be done that way.
  3. Use GENSYM function to generate a unique variable name.
(defmacro do-primes ((var start end) &body body)
  (let ((ending-value-name (gensym)))  ; We need GENSYM to give us a unique variable name
    `(do ((,var (next-prime ,start) (next-prime (1+ ,var)))
          (,ending-value-name ,end))
         ((> ,var ,ending-value-name))
      ,@body)))

MACROEXPAND-1

The MACROEXPAND-1 function compiles a macro and returns the list it would generate. (Note the single quote! Function calls evaluate their arguments, macros cannot.)

(macroexpand-1 '(when T (+ 1 3)))

See Also