I don't understand this code from the clojure 1.5 release notes. It uses the cond->
macro. For example, how would it translate into pre-1.5 code?
user=> (cond-> 1
true inc
false (* 42)
(= 2 2) (* 3))
6
Each step changes the result if the test is true, or leaves it alone if the test is false.
You could write this in 1.4 by threading anonymous functions:
user> (-> 1 (#(if true (inc %) %))
(#(if false (* % 42) %))
(#(if (= 2 2) (* % 3) %)))
6
Though the cond->
does not introduce new functions, instead it generates a binding form to be more efficient:
user> (let [g 1
g (if true (inc g) g)
g (if false (* g 42) g)
g (if (= 2 2) (* g 3) g)]
g)
6
and uses a gensym
for g
incase some of the forms use the symbol g
cond->>
is very similar, it just places the threaded symbol in a diferent place.
user> (let [g 1
g (if true (inc g) g)
g (if false (* 42 g) g)
g (if (= 2 2) (* 3 g) g)]
g)
6
which in this example gives the same result because *
and +
are commutative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With