What is the purpose of the clojure reduced
function (added in clojure 1.5, https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reduced)
I c
reduced
allows you to short circuit a reduction:
(reduce (fn [acc x]
(if (> acc 10)
(reduced acc)
(+ acc x)))
0
(range 100))
;= 15
(NB. the edge case with (reduced 0)
passed in as the initial value doesn't work as of Clojure 1.6.)
This is useful, because reduce
-based looping is both very elegant and very performant (so much so that reduce
-based loops are not infrequently more performant than the "natural" replacements based on loop
/recur
), so it's good to make this pattern as broadly applicable as possible. The ability to short circuit reduce
vastly increases the range of possible applications.
As for reduced?
, I find it useful primarily when implementing reduce
logic for new data structures; in regular code, I let reduce
perform its own reduced?
checks where appropriate.