0
votes

As far as I understand, a transducer is a function that transforms a reducer function before reduce takes place. In other words, (transduce transducer reducer collection) is equivalent to (reduce (transducer reducer) collection). So these two expressions

(reduce ((map inc) -) 0 [3 4 5])
(transduce (map inc) - 0 [3 4 5])

must return the same value. Right?

Wrong

(reduce ((map inc) -) 0 [3 4 5])    -15
(transduce (map inc) - 0 [3 4 5])    15

A bug or a feature? My version of Clojure is 1.8.0.

1

1 Answers

2
votes

It turns out that (transduce) implements a slightly different algorithm.

(reduce) calls (reducer aggregate element) for every element in the collection. A total of n calls for a collection of n elements.

(transduce) calls (reducer aggregate element) for every element and then for some reason calls (reducer aggregate) again, making n+1 calls. As a result, (transduce) doesn't work as expected with (-).