Chapter 2Advance Your Macro Techniques

Most of the macros you’ve seen so far have been small and straightforward. Wouldn’t it be great if they could all be like that? Unfortunately, as you do more and more with macros, the syntax you know so far can get unwieldy.

What if you had to write an assert macro like the one that comes with Clojure? Given what you know at this point, you’d need to do something like this:

advanced_mechanics/assert_no_syntax_quote.clj
 
(​defmacro​ ​assert​ [x]
 
(​when​ *assert* ​;; check the dynamic var `clojure.core/*assert*` to make sure
 
;; assertions are enabled
 
(​list​ '​when-not​ x
 
(​list​ '​throw
 
(​list​ 'new 'AssertionError
 
(​list​ '​str​ ​"Assert failed: "
 
(​list​ '​pr-str​ (​list​ '​quote​ x)))))))) ...

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.