reduced

added
1.5

ns
clojure.core

type
function

(reduced x)

Wraps x in a way such that a reduce will terminate with the value x

                ;; Suppose you want to short-circuit a sum like:
(reduce (fn [a v] (+ a v)) (range 10))
;;=> 45

;; So that it returns the sum of the integers if less than 100:
(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range 10))
;;=> 45

;; But the keyword :big otherwise:
(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range 20))
;;=> :big

;; The value returned by (reduced :big) short-circuits the reduction so that 
;; it returns the wrapped value without ranging over the entire sequence.
;; This is useful for infinite lazy sequences:
(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range))
;;=>:big

;; Which would otherwise not terminate.
            
                ;;re-implementing (some) using (reduce) and (reduced):

(defn resome [pred koll]
  (reduce (fn [_ c] (when-let [x (pred c)] (reduced x)))
          koll))

;;user> (resome #{4} [3 4 2 3 2])
;;>>> 4
;;user> (resome even? [3 41 25 3 2])
;;>>> true
;;user> (resome even? [3 41 25 3 27])
;;>>> nil