Macros
2010-12-11
Introduction
Lisp macros (and Scheme's hygienic macros in particular) are often ill-understood. Yet, if there is a single feature that makes the various Lisp dialects more powerful than other languages, it's macros. This part explains what macros are and how they work.
Macros, simply said, are code transformers. They take code as arguments, and return code as results. This allows extension of the programming language, without actually having to modify the language implementation. Unlike macros in many other languages, Scheme macros are written in Scheme itself and can use any feature present in the Scheme implementation. This makes macros very flexible, and can be used to simplify many programming tasks.
Macros, once written, are used much like functions. A macro invocation is a list whose first element is the name of the macro, and whose other elements are the arguments to the macro. However, the semantics of macros are very different from those of functions. Rather than evaluating the expressions that are passed as arguments, the expressions are passed to the macro unmodified. This is what allows a macro to perform code transformations.
Another difference between macros and functions becomes apparent when compiling programs. Macro expansion is performed at compile time, whereas functions are called only when the program is run (of course, function calls from inside macros will be performed when the macro is expanded).
There are different macro systems in use with various Scheme
implementations. The ones discussed here are the macros as
described by the revised5 report
(syntax-rules
macros), and the defmacro
macros
(from Common Lisp).
Defmacro
defmacro
macros are not actually part of
Scheme (they are from Common Lisp). However, many Scheme implementations
support them, and they are conceptually simple. I will explain
defmacro
macros first, before moving on to Scheme's
syntax-rules
macros.
Syntax-Rules
The Revised(5)
Report on the Algorithmic Language Scheme specifies hygienic macros
using the syntax-rules
mechanism. These macros are called
&ldquot;hygienic&rdquot;, because they do not allow for variable
capture the way defmacro
macros do. The general consensus
is that this makes them less powerful, but also less tricky to
write.