This page is for discussing how and when to use macros and for examples of macro use, see DoWeWantLispMacros for whether or not they should be used.
Uses of Macros
Macros are/should-be used for these reasons:
- to deal with new data sub-languages (hide quote and quasiquote)
- to introduce new binding operators
- to specify control among the subexpressions of a form.
## this is only a limited view on macros. See my comment on macros and CLOS later on this page.
Macro Systems
There are three main macro systems in use:
- CommonLisp macros are functions that transform EssExpressions to EssExpressions using QuasiQuote and UnQuote. See CommonLispMacroExamples
- The SchemeLanguage standard macro system, called SyntaxRules, are safe from variable capture (called hygiene) and written using a very clear pattern matching style. However they cannot do everything that can be done in CommonLisp macros. See DefineSyntax for some exposition and SchemeMacroExamples for some examples.
- The SchemeLanguage SyntaxCase macro system offers the benefits of both: pattern matching and hygiene when you want, with the ability to circumvent hygiene when so desired. See SchemeMacroExamples.
Since I know that I use macros for deep, meaningful stuff, here are "prototypes" for the ones I consider interesting:
(def-synonym-function synonym original) (def-pipe-function function-name (input-stream output-stream &rest other-args) &body body) (def-enumerated-value-domain control &rest data) (let-gensyms symbols &body body) This one is a very common idiom, except it's usually called something else. (struct-comparison-predicate struct-name reducer-name &rest fields) I need to rework the interface to this one. (successive-character-predicate-parser input (&body predicates) &body body) And even more so for this one.Three of these are convenience utilities; one is an "inconvenience utility" which I don't actually use anymore. One concisely defines a whole set of functions and symbols which relate to each other, in a manner which I very often want. The remaining two are nano-languages to simplify the writing of certain sorts of code. Most of these, I use quite often. I could expound the above at great length, but I expect it's not necessary to answer your question. -- DanielKnapp
Other common macros are:
(when-bind var condition &body body)bind var to the result of condition and evaluate body if the condition returned true
(with-collectors (collectors &body)COLLECTORS is a list of symbols, for each element of COLLECTORS a new function is introduced in BODY, these functions collect their arguments. WITH-COLLECTORS returns all of the collected arguments as multiple values. ie:
(with-collectors (a b)