Saturday, February 19, 2011

Clojure: mdef macro

I don't believe this macro is particularly useful. In principle, this macro should not have been written at all. If fails the very first questions we should ask ourselves before writing a macro, that is to say the macro is not necessary. If you really need a macro to specify multiple special variables, you are probably getting the design wrong.

However, it is easy enough to demonstrate some basic techniques. In particular, the idea is how we quote/unquote in nested ways. Most basic examples on macros show how ~ unquotes a symbol. In fact ~/unquote is more general: it "reverts" to standard clojure evaluation.

Code in an unquote is just regularly executed at compile time. A particular case is when we write ~foo it is equivalent to (unquote foo) where foo is just a symbol which is evaluated to its value as it is the rule with Clojure. The do form is quasiquoted, then we ~@ the list built with the loop.

Inside the loop, we use ` once again: we could have built the list without using "templating", just using regular clojure operations [(list 'def ...)]. In fact, it is entirely possible to build macros without using ` and ~ and simply "building" the s-expressions representing the code. It is usually believed that code written this way is less clear.

Of course, the macro could have been written in a more compact way. However, I think that this way is rather readable and shows clearly the point I intended to make.

Technorati Tags: , , ,

No comments: