Hacker News new | ask | show | jobs
by kazinator 3382 days ago
Macros don't "change source code". That is a serious, but common misconception: that they are somehow self-modifying code.

Lisp macros give meaning to syntax that doesn't previously have meaning. In this regard, they are the same as functions.

(foo (boonly) blarg) doesn't have any meaning because foo hasn't been defined.

We can fix that by writing a function foo. Then (boonly) and blarg have to be valid expressions and we are good.

Or we can make it mean something can by writing a macro foo. The macro foo is a function that will operate on the entire form (foo (boonly) blarg) and calculate a replacement for it. The Lisp form expander (a feature of the compiler or interpreter) will call the macro and accept its return value as the replacement for the macro call. Then, the replacement is scanned for more macros; the entire process removes all macros until all that is left is special operators and functions.

A practical example of a macro is the ANSI Common Lisp standard macro called loop which provides a syntax for iterating variables, stepping through collections, and taking various actions or gathering results:

  (loop for bit in '(0 3 7 13)
        for mask = (ash 1 bit)
        summing mask) -> 8329 

This entire looping mini-language is implemented in the loop macro. When you call (loop ... args) the macro takes over, analyzes the phrases and compiles them into other syntax.