Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

purpose of clojure reduced function

Tags:

clojure

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 can't find any examples for it. The doc says:

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

There is also a reduced? which is acquainted to it

Returns true if x is the result of a call to reduced

When I try it out, e.g with (reduce + (reduced 100)), I get an error instead of 100. Also why would I reduce something when I know the result in advance? Since it was added there is likely a reason, but googling for clojure reduced only contains reduce results.

like image 825
shaft Avatar asked Aug 03 '14 17:08

shaft


People also ask

What is a lazy sequence Clojure?

However, Clojure supports lazily evaluated sequences. This means that sequence elements are not available ahead of time and produced as the result of a computation. The computation is performed as needed. Evaluation of lazy sequences is known as realization.

What is a transducer Clojure?

Transducers are composable algorithmic transformations. They are independent from the context of their input and output sources and specify only the essence of the transformation in terms of an individual element.

Is Vector a Clojure?

Clojure collections "collect" values into compound values. There are four key Clojure collection types: vectors, lists, sets, and maps.


1 Answers

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.

like image 93
Michał Marczyk Avatar answered Oct 18 '22 13:10

Michał Marczyk