Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

reduce

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?

like image 726
KobbyPemson Avatar asked May 02 '14 17:05

KobbyPemson


1 Answers

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"

like image 161
GregA100k Avatar answered Sep 20 '22 06:09

GregA100k