Macroexpansion

Manually walking through a macroexpansion, as you saw in the previous section, is fairly tedious work. But as you might guess, you don’t always have to do it manually. Clojure exposes to users the very same macroexpansion tools that it uses internally. This way, you can have a look at the expression a macro will generate, without having to go through that whole process you just saw.

macroexpand-1 is the simplest of these tools, converting a macro expression to its resulting expression.

basics/macroexpand_1.clj
 
(​macroexpand-1​ '(​when​ (​=​ 1 2) (​println​ ​"math is broken"​)))
 
;=> (if (= 1 2) (do (println "math is broken")))
 
 
(​macroexpand-1​ nil)
 
;=> nil
 
 
(​macroexpand-1​ '(​+​ 1 2))
 
;=> (+ 1 2)

Note the similarity ...

Get Mastering Clojure Macros now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.