Clojure Macro Explorations: cond->

Some notes I’ve taken on my journey to really understand Clojure macros. Today I basically walked through the cond-> macro in clojure.core, and these are my notes as I figured out how it works.

;; cond-> from clojure/core.clj
;; This is one of the easier to understand threading macros in the source code, even
;; if it’s use isn’t immediately obvious. However, I’m working on figuring out how
;; to really leverage macros, and the best examples are in the source code.
;; cond-> is a variation of the thread-first function ->, which executes a sequence
;; of forms, while passing in the previous value as the first argument.
;; For example, the following code:
;; (-> 1 inc inc (+ 3)) basically expands to something equivelent to:

;; Pedantic note: This really expands to (+ inc (inc 1)) 3), but I
;; think the above is easier to understand, and seques better.
;; The cond-> macro does something very similar, but it allows
;; putting GUARDS on each step of the computation; if the GUARD is
;; true, then that step executes, else it is skipped.
;; One thing to node is that the GUARD can NOT access the current
;; value of the computation. Thus, the use of cond-> seems to be
;; something like CASE statements where multiple branches can be chained.
;; Let’s compare -> to cond-> in terms of expansion…

;; Keep an eye on the above right expansion as you browse the macro:
;; G in the macro is x above
;; initial in the macro is 1 above
;; pstep is the function that creates the (if X (f x) x) code.

Leave a Reply