liveBook · Manning

Reductions

As explained in Clojure: The Essential Reference

reductions is a Clojure function that returns the intermediate accumulator results produced by a reduction.

Use `reductions` when you need the running results of a calculation, not just its final answer. Like `reduce`, it accepts a reducing function and a collection, optionally preceded by an initial accumulator value. It returns the accumulator at each step; when an initial value is supplied, that value appears first. section 3.5.4

Running sum

`(reductions + (map #(* % %) (range 5)))` returns `(0 1 5 14 30)`. Each result adds the next square to the sum so far. The last result is the final sum that `reduce` would return. section 3.5.4

(defn next-average [[cnt sum avg] x]            ; #1
  (let [new-cnt (inc cnt)
        new-sum (+ sum x)
        new-avg (/ new-sum (double new-cnt))]
    [new-cnt new-sum new-avg]))

(defn stock-prices [values]
  (reductions next-average [0 0 0] values))     ; #2

(stock-prices [5.4 3.4 7 8.2 11])               ; #3
;; ([0 0 0]
;;  [1 5.4 5.4]
;;  [2 8.8 4.4]
;;  [3 15.8 5.266666666666667]
;;  [4 24.0 6.0]
;;  [5 35.0 7.0])

A running-average calculation uses `[count sum average]` as its accumulator. The initial vector appears in the output, followed by one updated vector per price. section 3.5.4

A reducing function can also use `reduced` to stop early. In the shown example, accumulation stops when an item exceeds 5, leaving `(0 1 3 6 10 15 21)`. If only the final value matters, use `reduce` instead: the supplied benchmark shows it is substantially faster than taking the last value of `reductions`. section 3.5.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains both arities and stepwise accumulation, then shows structured accumulator state, early termination, and a performance comparison.
Examples
Shows cumulative sums of squares, running averages of prices, early termination, and a benchmark against reduce.
What it assumes
Builds on Clojure collections and functions while defining the accumulator as the result so far.
What you can do after
Apply it via Clojure's reductions to inspect cumulative results or produce running calculations.
How it connects
Relates reductions to reduce, accumulators, map, folds, and reduced.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.