What is the purpose of clojure.core.reducers / reduce?

A slightly modified version of reduce was introduced with reducers , clojure.core.reducers/reduce (short r/reduce ):

 (defn reduce ([f coll] (reduce f (f) coll)) ([f init coll] (if (instance? java.util.Map coll) (clojure.core.protocols/kv-reduce coll f init) (clojure.core.protocols/coll-reduce coll f init)))) 

r/reduce differs from its main brother only in that it uses (f) as the initial value when none is provided, and it passes reduce-kv to the kernel for the cards.

I don’t understand what might be the use of such an unusual special reduce , and why it should be included in the reducer library.

Curiously, r/reduce not mentioned in the two introductory blog posts, as far as I can tell (, second ). Official documentation notes

In general, most users will not directly access r / reduce and instead prefer r / fold (...) However, it may be useful to perform accelerated reduction with fewer intermediate results.

Not sure what the last sentence hints at.

In what situations can r/reduce deal with what kernel reduction cannot? When can I achieve r/reduce with conviction?

+5
source share
1 answer

Two possible reasons:

  • He has different - better! - semantics than clojure.core/reduce in sequential sequential case. During his 2014 presentation, Conge Rich Hickey asked: "Who knows what reduce semantics is when you call it a collection and there is no initial meaning?" - follow this link for the exact place in the presentation - and then described the specified semantics as a “funny, complicated rule” and “one of the worst things that he ever copied from Common Lisp” - cf. General Lisp reduce contract . The presentation concerned converters, and in the context of the remark there was a discussion of transduce , which has a simpler and simpler contract; r/reduce as well.

  • Even without considering the above,, it’s nice to have a reduce version with a contract very close to a fold contract. . This allows you to simply "try one, try another" benchmarking with the same arguments, and just change one mind. "

+3
source

Source: https://habr.com/ru/post/1244945/


All Articles