Writing a Control Flow Macro
Clojure provides the if special form as part of the language:
(if (= 1 1) (println "yep, math still works today")) | |
| yep, math still works today |
Some languages have an unless, which is (almost) the opposite of if. unless performs a test and then executes its body only if the test is logically false.
Clojure doesn’t have unless, but it does have an equivalent macro called when-not. For the sake of having a simple example to start with, let’s pretend that when-not doesn’t exist and create an implementation of unless. To follow the rules of Macro Club, begin by trying to write unless as a function:
src/examples/macros.clj | |
; This is doomed to fail... | |
(defn unless [expr form] | |
(if expr nil form)) ... |
Get Programming Clojure, 2nd Edition 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.