Tuesday, 20 November 2007

The let macro

I recently had the opportunity to read (and unfortunately let go of) Lisp in Small Pieces (LiSP). Fortunately, not before I had the opportunity to have my eyes opened.

One of the most basic useful units in any programming language are variables. Lisp has the concept of bindings which are an association between a name and the bound thing. In Lisp, you can bind functions as well as variables which is why the preceding definition (lifted from CLHS) is so generic. The LET operator is the mechanism to accomplish lexical binding as one is used to in other languages. So if one were to write the following n C++:


int a = 5;

The equivalent Lisp would be:

(let ((a 5)) ... )

Where the ellipses denote the scope in which the binding is valid.

For most people, thats where it ends: "Ok, so now I can declare variables. Yay." And for me, that was the case until I picked up LiSP. LiSP develops a Scheme-like language whose definition is in Scheme to start with. But did you know that the LET operator can be defined if all you have are lambda functions? I sure didn't! For example:

(let ((x 5) (y 2)) ...)
; becomes
((lambda (x y) ...) 5 2)

Wow! For those of you who missed it, the implementation of LET can be a call of a lambda function. Now of course there are little details missing here like the fact that you need some way of looking up the bindings, but that is fairly easy if implementing the interpreter.

LiSP is full of these little insights and I really need to buy a copy for myself. Cherish the book if you have it!

No comments: