I am still learning Clojure on the side (the first post was about persistent collections). This month I got to macros. Every Lisp book says macros are the big feature, and the same books also say “do not write macros”. I wanted to see both sides with a small real example. All code here is Clojure 1.8.
Code is data
Clojure code is written as Clojure data. A function call is a list. A let binding is a vector. The
reader turns text into these data structures before anything is compiled.
user=> (def form (read-string "(+ 1 2)"))
#'user/form
user=> (type form)
clojure.lang.PersistentList
user=> (first form)
+
user=> (type (first form))
clojure.lang.Symbol
user=> (eval form)
3
This is what “homoiconic” means. The program is a list, and you already have all the list functions to
build and change it. In Java, the closest thing is an annotation processor or bytecode tools. In Python you
can use the ast module. Both work, but they use a separate tree type. In Clojure it is the same lists and
vectors you use every day.
A macro is a function that runs at compile time. It gets the forms (unevaluated), and returns a new form. The compiler then compiles the returned form in place of the macro call.
A first macro: unless
Clojure already has when-not, but unless is a good first exercise.
(defmacro unless [test & body]
`(if ~test nil (do ~@body)))
Three pieces of syntax:
`is syntax-quote. It builds a form like a template. It also namespace-qualifies symbols, sostrinside it becomesclojure.core/str.~is unquote. It puts the value oftestinto the template.~@is unquote-splicing.bodyis a list of forms, and~@inserts them one by one, not as one list.
Use macroexpand-1 to see what you get:
user=> (macroexpand-1 '(unless (= 1 2) (println "a") (println "b")))
(if (= 1 2) nil (do (println "a") (println "b")))
if and do are special forms, so syntax-quote leaves them as they are.
This needs a macro because a function evaluates all its arguments first. If unless were a
function, (println "a") would run before unless even sees the test. Controlling when (or whether) code
runs is the thing a function cannot do.
A timing macro, the wrong way first
I wanted something that prints how long a block takes, with a label, and returns the block’s value.
clojure.core/time exists, but it has no label. My first try:
(defmacro with-timing [label & body]
`(let [start (System/nanoTime)
result (do ~@body)]
(println ~label (/ (- (System/nanoTime) start) 1e6) "ms")
result))
Calling it fails:
CompilerException java.lang.RuntimeException: Can't let qualified name: user/start
Syntax-quote turned start into user/start, and you cannot bind a qualified symbol in let. This error
is Clojure protecting me. In Common Lisp the code would compile, and then start could clash with a
start in the caller’s code. That clash is called variable capture, and it is the classic hygiene problem
with macros.
The right way: gensyms
Add # to the end of a symbol inside syntax-quote. Clojure replaces it with a unique generated name
(an auto-gensym):
(defmacro with-timing [label & body]
`(let [start# (System/nanoTime)
result# (do ~@body)]
(println ~label (/ (- (System/nanoTime) start#) 1e6) "ms")
result#))
user=> (with-timing "sum" (reduce + (range 1000000)))
sum <elapsed> ms
499999500000
I replaced the time with <elapsed>. A single run at the REPL says little anyway.
Now expand it:
user=> (macroexpand-1 '(with-timing "sum" (reduce + (range 10))))
(clojure.core/let [start__1234__auto__ (java.lang.System/nanoTime)
result__1235__auto__ (do (reduce + (range 10)))]
(clojure.core/println "sum" ...)
result__1235__auto__)
I shortened the output a little. The numbers in the names change each time. The point is that the caller
can have their own start or result and nothing clashes.
Auto-gensyms only work inside one syntax-quote. If a macro builds its form from several pieces, call
(gensym "start") yourself and put the symbol in with ~.
Evaluate arguments once
Another common bug: using ~x twice in the template. If the caller passes (fetch-something), it runs
twice. Bind it once in a let with a gensym, and use the gensym after that.
Capturing on purpose
Sometimes you do want the caller to see a name, for example an anaphoric macro that binds it. Then you
write ~'it, which puts a plain unqualified symbol in. I would avoid this. It surprises readers.
Debugging macros
macroexpand-1expands one level. Start here.macroexpandexpands until the outer form is no longer a macro, but does not touch inner forms.clojure.walk/macroexpand-allexpands everything. Good to read, but very noisy withletandfn.- Quote the form you pass in (
'(...)), or it will be evaluated first. - Errors from macro-generated code point to the line of the macro call, not the template. When an error makes no sense, expand the call and read the result.
Functions first
The timing example could be a function:
(defn timed [label f]
(let [start (System/nanoTime)
result (f)]
(println label (/ (- (System/nanoTime) start) 1e6) "ms")
result))
(timed "sum" #(reduce + (range 1000000)))
The only cost is the #(...). In exchange you get something you can pass to map, store in a var, and
use with apply. A macro cannot do any of these:
user=> (map unless [true false])
CompilerException java.lang.RuntimeException: Can't take value of a macro: #'user/unless
This is close to how I write Python decorators: wrap a function, do not rewrite code.
My rule now, which is the same rule most Clojure people give:
- Write a function.
- If the only problem is that the caller has to wrap code in
fn, that is usually fine. Keep the function. - Write a macro only when you must control evaluation (skip it, delay it, repeat it), or when you need to
create new binding forms (like
letorwith-open), or for a definition form likedefroute. - When you do write one, keep the macro thin. Let it expand into a call to a normal function that does the real work. Then most of the logic is testable without macros.
with-open in clojure.core is a good model for point 3. It binds a name and makes sure .close runs in
finally, and that cannot be done with a plain function call without making the caller write a lambda.