Macros to the Rescue

We can indeed, but to get it done we need to step back and forget about functions and argument evaluation for a second and think about what we’re trying to do with arithmetic-if. What we really want to do is write something like this:

 (arithmetic-if rating
  (println ​"Good book!"​)
  (println ​"Totally indifferent."​)
  (println ​"Run away!"​))

but execute something like this:

 (​cond
  (pos? rating) (println ​"Good book!"​)
  (zero? rating) (println ​"Totally indifferent."​)
  :else (println ​"Run away!"​))

Wouldn’t it be great if we could somehow preprocess our Clojure code just before it gets compiled? We could take advantage of the preprocessing step to turn our arithmetic-if expression into the equivalent cond expression. ...

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.