Programming Lisp

Shortly after I started learning Lisp (Scheme really) of which I only knew that it involved parentheses, I started hearing (and reading) that Lisp was a programmable programming language. For example, from the preface of Paul Graham’s On Lisp:

It’s difficult to convey the essence of a programming language in one sentence, but John Foderaro has come close:

Lisp is a programmable programming language.

Though I understand what it means, I couldn’t see why Lisp was more programmable than say, Java. What I was hearing was just by adding new APIs, I was extending the language and even inventing a new one. The SICP authors for example, at some point mention this new language built on top of Scheme: Picture. It’s a language for manipulating images, rotating them, creating new images using existing ones, etc. All I saw was a new function for making interesting things with pictures. Though I found it interesting, it wasn’t very satisfying in terms of meta-programming.

I think Scheme and Lisp are beautiful languages, it was love at first sight :-) . But when I’m doing my little silly programs in these languages, I cannot honestly say that I am programming Lisp. Certainly I’m programming *in* Lisp, but not programming *it*. Could it be that Paul Graham and everyone else in the Lisp community had a looser definition of what it means to program a programming language? I doubt it so something was not right

Then the SVP group moved on from SICP and Scheme to Common Lisp and more specifically, to one of the most interesting aspect of Lisp that we had left out during our Scheme run: macros. This is when it hit me, this is where the notion of programming a programming language was hiding. Lisp macros are more than C macros where most of what’s happening is string substitution. With Lisp macros you can write code that expands into Lisp functions. In fact, you can write macros that expand to macros, that expand to macros, eventually expanding to actual code. This is something you clearly cannot do in Java for example.

Let’s say “if” is not working for you, and you want an “unless” instead. Instead of saying


if( statement ) {
    ;
}
else {
    do();
}

You wanted to say


unless( statement ) {
    do();
}

Since this is a very simple macro, I suppose you could do it even in C, using #define, but still not in Java. In Lisp this is a “trivial” thing to do but Lisp books have whole chapters on macros, and it gets more interesting than just trivial stuff.

The unless macro:


(defmacro unless (condition &body body)
  `(if (not ,condition)
      (progn ,@body)))

Then I can say:


(unless (= A B) do)

Peter Seibel’s Practical Common Lisp has an example where he builds a unit testing framework using macros, in 26 lines, including comments and empty lines! A thing of beauty.

Leave a Comment