Zchpyvr
Zchpyvr

Reputation: 1129

Clojure-New Cond Macro?

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

Upvotes: 16

Views: 2369

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91534

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.

Upvotes: 27

Related Questions