O'Reilly logo

Mastering Clojure Macros by Colin Jones

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)))))))) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required