Explanation of macros; Haskell macros

Lex Spoon lex at cc.gatech.edu
Fri Oct 24 11:48:44 EDT 2003


This thread has seemed to miss the biggest advantage of macros.  Most
examples so far are cases where the macro buys you faster code.  This
is not extremely exciting, IMHO, because a better compiler can often
accomplish the things that are described.  If you care that much about
performance then surely you want to be using a good optimizing
compiler, and a good compiler will surely know about, e.g., for loops
that go across constant ranges.  I tend to think of macros as bad
style for this kind of thing, unless it's very clearly a performance
problem you are having.  Macros often look like functions, but they
don't act like them, and it's very easy to introduce bugs with them.

A much bigger advantage of macros is that you can literally extend
the language.  For example, it is nice to be able to type something
like this:

     (regex (| h H)  "ello, "  (| w W)  orld  (? "!"))


To allow this in the nicest way requires using a macro for 'regex.
Without macros, you can still do it:

     (regex '(| h H)  "ello, "  (| w W)  orld  (? "!"))

but now this guy is going to get compiled at runtime, and you get into
the issue of trying to save the compiled regex somewhere ahead of
time.  And while regexes themselves compile pretty quickly, suppose
it's something more like:

     (parser
          (grammer
             ;;... a BNF grammer ...



I also loved the example of both printing a statement and executing
it, which is extremely useful for assertion checking.  You can't
really do this properly without macros.



-Lex




More information about the Python-list mailing list