Clojure gear library - bending with max

I am trying to convert the following example to the new Clojure 1.5 gearbox library:

(reduce max (map inc (range 10))) ;=> 10 

When I change it, I get the following error:

 (r/fold max (r/map inc (range 10))) ;ArityException Wrong number of args (0) passed to: core$max clojure.lang.AFn.throwArity (AFn.java:437) 

Can someone give me the right solution?

+6
source share
1 answer

Note that it works if you substitute max with + .

 (r/fold + (r/map inc (range 10))) ; => 55 

The difference is that, unlike + max there is no case for calling without arguments. r/fold requires a union function - i.e. max - provide the identifier value when called without arguments. For * it 1 , for + it 0 .

A potential solution would be to define a max' , which acts like max , but when called without arguments, it returns a negative infinity identification element for the function max .

 (defn max' ([] Double/NEGATIVE_INFINITY) ([& args] (apply max args))) (r/fold max' (r/map inc (range 10))) ; => 10 

The same result can be achieved using the r/monoid .

 (r/fold (r/monoid max #(Double/NEGATIVE_INFINITY)) (r/map inc (range 10))) 

For further discussion, see Gearboxes - a library and a model for processing collections , section Simplicity is an opportunity.

+10
source

All Articles