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.
clojure
nybon
source share