What does the 'reduced' function do and how to use it

In the answer to this question the responder uses the function reduced

(defn state [t] (reduce (fn [[s1 t1] [s2 t2]] (if (>= t1 t) (**reduced** s1) [s2 (+ t1 t2)])) (thomsons-lamp))) 

I looked at the doc and source and can't fully grok it.

(defn reduced "Wraps x in a way such that a reduce will terminate with the value x" {:added "1.5"} [x] (clojure.lang.Reduced. x)) 

In the example above I think (reduced s1) is supposed to end the reduction and return s1.

Is using reduce + reduced equivalent to hypothetical reduce-while or reduce-until functions if either existed?

2

1 Answer

Reduced provides a way to break out of a reduce with the value provided.

For example to add the numbers in a sequence

(reduce (fn [acc x] (+ acc x)) (range 10)) 

returns 45

(reduce (fn [acc x] (if (> acc 20) (reduced "I have seen enough") (+ acc x))) (range 10)) 

returns "I have seen enough"

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like