Function to reduce time in clojure?

I am new to Clojure programming and would like to know what an idiomatic way to do the following:

  • I would like to summarize a set of numbers nums , which can contain a large number of numbers, let's say that only positive numbers exist.

  • I do not need the exact amount if the amount is very large. For example, if the sum of the numbers is greater than 9999, I simply return 10000 without summing the remaining numbers at all.

If I implement it with some OO languages, such as Java, I can do it as shown below:

 private int sum(int[] nums) { int sum = 0; for(int n : nums) { if(sum > 9999) { sum = 10000; break; } else { sum += n; } } return sum; } 

A naive implementation in Clojure might look like this:

 (let [sum (reduce + nums)] (if (> sum 9999) 10000 sum)) 

However, it seems that this scares some processor resource to summarize the entire set of numbers, which is undesirable. I am looking for something like the “take into account” function, but to reduce it, but I cannot find it. There is something like:

 (reduce-while pred f val coll) 

Or is there any other Clojure idiomatic way to solve this problem? I think that the solution can be applied to a set of problems requiring similar logic.

Any comments are welcome. Thanks.

+7
clojure
source share
2 answers

If you are using Clojure 1.5.x, you can use the new reduced function :

 (reduce #(if (> %1 9999) (reduced 10000) (+ %1 %2)) nums) 
+15
source share

One of the lesser-known features of Clojure seems reductions . It will give you all the intermediate results of your calculations:

 (reductions + (range 4)) ;; => (0 1 2 3) (reduce + (range 4)) ;; => 3 

The last reductions ' result seq element will be a reduced value. There are several ways to force a predicate, for example. using some :

 (let [sums (reductions + nums)] (if (some #(> % 9999) sums) 10000 (last sums))) 

The reduce / reduced version given by @ leonid-beschastny is probably faster (without lazy overhead, reducers, ...), but this will work in earlier versions of Clojure.

+10
source share

All Articles