purpose of clojure reduced function

前端 未结 1 678
春和景丽
春和景丽 2021-02-19 10:59

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

1条回答
  •  感动是毒
    2021-02-19 11:51

    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.

    0 讨论(0)
提交回复
热议问题