Staying Out of Trouble

One thing should be clear: macros are hard to get right—much harder than plain functions. With an ordinary function you write the code and it gets executed. With a macro you write the code that writes the code that gets executed. Implicit in this two-step process is that macros make themselves felt at two distinct times. There’s the moment when the macro is expanded—when it is writing the code—and then there’s the moment when the generated code is executed. We can see that distinction here:

 (​defmacro​ mark-the-times []
  (println ​"This is code that runs when the macro is expanded."​)
  `(println ​"This is the generated code."​))
 
 ;; Expand the macro and you get the 1st println
 ;; but not the 2nd.
 
 (​defn​ use-the-macro ...

Get Getting Clojure 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.