Monday, February 18, 2008

My first macro-writing macro

Any trained monkey can write a Common Lisp macro. They're pretty simple. But last night, I wrote a macro that further defines another macro. In about 40-ish lines, I can now access data from my database in a single form:

(with-users ((user-read-many) :name n :details d)
(format t "~a: ~a~%" n d))

That will print out the names and details of all users in the system I'm building. I'm doing this as part of a little web application that I'm building for my own education. The idea is that the above code can be used within HTML page generators to print out what I want from the database.

As far as that macro goes, I would never have succeeded without C-c RET, which triggers SLIME's MACROEXPAND-1. I could be hacking at this macro, and in a split second have the result of using it there, on my screen.

It was some of the slowest code I'd ever written in my life. No, I'm not talking about run-time efficiency, I'm talking about how slowly I was typing code in. Getting my head to operate in two layers of back-ticks is a mind-bending experience.

The SLIME scratch buffer also helped. I wouldn't have even known about the SLIME scratch buffer without the SLIME selector.

The SLIME selector is a simple mode-switcher, containing options to go to the most recent Lisp buffer, or the REPL, or bring up the scratch. This line in your .emacs will enable it:

(define-key global-map (kbd "<f12>") 'slime-selector)

Some people use C-c s instead, but I like the one-key access myself.

So yeah, two-line database access is pretty awesome.

No comments: