Common Lisp - Macros

Macros

A macro in Lisp superficially resembles a function in usage. However, rather than representing an expression which is evaluated, it represents a transformation of the program source code. The macro gets the source it surrounds as arguments, binds them to its parameters and computes a new source form. This new form can also use a macro. The macro expansion is repeated until the new source form does not use a macro. The final computed form is the source code executed at runtime.

Typical uses of macros in Lisp:

  • new control structures (example: looping constructs, branching constructs)
  • scoping and binding constructs
  • simplified syntax for complex and repeated source code
  • top-level defining forms with compile-time side-effects
  • data-driven programming
  • embedded domain specific languages (examples: SQL, HTML, Prolog)

Various standard Common Lisp features also need to be implemented as macros, such as:

  • the standard SETF abstraction, to allow custom compile-time expansions of assignment/access operators
  • WITH-ACCESSORS, WITH-SLOTS, WITH-OPEN-FILE and other similar WITH macros
  • Depending on implementation, IF or COND is a macro built on the other, the special operator; WHEN and UNLESS consist of macros
  • The powerful LOOP domain-specific language

Macros are defined by the defmacro macro. The special operator macrolet allows the definition of local (lexically scoped) macros. It is also possible to define macros for symbols using define-symbol-macro and symbol-macrolet.

Paul Graham's book On Lisp describes the use of macros in Common Lisp in detail.

Read more about this topic:  Common Lisp