5

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?

Community
  • 1
  • 1
KobbyPemson
  • 2,519
  • 1
  • 18
  • 33
  • The source for `reduced` doesn't tell you a whole lot - you have to look at the source for `reduce` to really know what's going on. – Alex May 02 '14 at 18:39
  • Even the source to `reduce` calls out to some implementation methods. – noisesmith May 02 '14 at 20:26

1 Answers1

5

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"

GregA100k
  • 1,385
  • 1
  • 11
  • 16