`transduce` transforms a collection while reducing it to a result. It resembles `reduce`, but takes the transformation as a separate `xform` argument. That separation lets a transducer chain be reused with other collection-processing operations. section 7.2.1 section 7.2
The call is `(transduce xform f coll)` or `(transduce xform f init coll)`:
- `xform` is a transducer, often made by composing collection operations such as `filter` and `map` without supplying them a collection. section 7.2 section 7.2.1
- `f` combines an accumulator and the next item. Optional `init` supplies the starting accumulator; otherwise, `f` must supply one when called with no arguments. section 7.2.1
- `coll` accepts collections supported by `reduce`, including `nil`, Java `Iterable` values, and arrays, but not transients or scalar values. With `nil` input, the result is based on `init` or the zero-argument call to `f`. section 7.2.1
Separate transformation from reduction
`(reduce + (map inc (filter odd? (range 10))))` → `30` `(transduce (comp (filter odd?) (map inc)) + (range 10))` → `30` Both sum incremented odd numbers. In the second expression, `comp` supplies the transformation chain and `+` supplies the final reduction. section 7.2.1
Completion matters: after processing the input, `transduce` calls the transformed reducing function with one argument. A reducing function’s own one-argument behavior may therefore change the result. Use `completing` to provide identity completion or a deliberate final step. A nil `xform` or `f` raises `NullPointerException`; a custom transducer missing a required arity can raise `ArityException`. section 7.2.3 section 7.2.1
Control the final call
`(transduce (map inc) - 0 (range 10))` → `55` `(transduce (map inc) (completing -) 0 (range 10))` → `-55` Here `completing` replaces the reducing function’s one-argument completion behavior with identity. section 7.2.3
