Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a reduce function from processing the list once the desired accumulation has been reached?

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.

like image 284
Amogh Talpallikar Avatar asked May 23 '14 06:05

Amogh Talpallikar


Video Answer


1 Answers

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])
like image 134
Jonas Avatar answered Oct 08 '22 18:10

Jonas