In the procedural world, if I have to find the first item of a list that meets a test, I would just use break
or return
.
In Clojure, when I am processing a list using reduce
to find that first value, won't it be inefficient if I continue and process the entire list?
For example: validating a list of dictionaries for errors; each dictionary has a key called count
. Now the total sum of these count fields in the list should not exceed a certain value. How do I find the first item in the list where the sum exceeds the limit ?
Ideally, I would use reduce
and maintain a running total; as soon as the total exceeds the limit, I would like to stop there (which I can't figure out how to do).
Also, the return value of the reduce will be the sum till now everytime but I would need to return the index at the end of all.
You can use the reduced
function to terminate a reduction:
(reduce (fn [sum x]
(if (> sum 10)
(reduced 10)
(+ sum x)))
0
[1 2 3 4 5 6 7 8 9 10])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With