Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure-New Cond Macro?

Tags:

clojure

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
like image 762
Zchpyvr Avatar asked Dec 11 '12 23:12

Zchpyvr


1 Answers

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.

like image 60
Arthur Ulfeldt Avatar answered Nov 10 '22 23:11

Arthur Ulfeldt