POSTS

Beginning Practical Common Lisp

Spent last night reading Practical Common Lisp, stopped at chapter 3. Found chapter 2, creating a simple database with Lisp, quite exhilarating as I was taken from Hello World right up to defining macros, with simple (albeit contrived) examples of how they could help with code compression. I’ve always been kinda confused by their inner workings, but Peter Seibel’s explanation of explanation of how macros worked almost made sense to me, although that could be just due to the late hour.

Let me try to explain macros to see if I get it.

Macros are a form of code substitution. Any lisp code passed to a macro is not evaluated by the compiler initially, but rather, given to the macro first. The macro can manipulate the given lisp code just like any data structure, because lisp code always comes in a data structure. After the macro is done, the compiler then evaluates the output of that macro only.

This example from the book really helped:

CL-USER> (format t "Hello, world!")
Hello, world!
NIL
CL-USER> (defmacro backwards (expr) (reverse expr))
BACKWARDS
CL-USER> (backwards ("Hello, world!" t format))
"Hello, world!"
NIL
CL-USER> (macroexpand-1 '(backwards ("Hello, world!" t format)))
(FORMAT T "Hello, world!")
T

The CL-USER> prompt shows what I’m typing into the compiler, with the subsequent lines being the output from running each expression. As explained in the book:

  1. line 1 contains the code to print “Hello, world!”
  2. line 4 defines a macro that reverses the order of any code given to it
  3. line 6 passes the same expression used in line 1 into our macro
  4. line 9 reveals the actual code as produced by the macro just prior to compilation

In summary, macros give you the fundamental capability to rework a Lisp expression any way you see fit. The backwards macro above creates a crazy little language where any expression you type is the reverse of what you would normally type in Common Lisp. They can also be used in more useful ways, such as generating boilerplate code.