liveBook · Manning

Accumulator

As explained in Clojure: The Essential Reference

An accumulator is the value representing the result of a reduction after processing some prefix of the input.

An accumulator is the result-so-far in a reduction, often named `acc`. A reducing function takes that result and the next collection item, then returns the result to carry forward. The accumulator need not be a number: it can be a map or another value suited to the task. section 3.5.4

See each result-so-far

`(reductions + (map #(* % %) (range 5)))` returns `(0 1 5 14 30)`. Each value includes one more square; `reduce` returns only the final value, `30`. 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 carries a vector of count, sum, and average as its accumulator. An explicit initial value, `[0 0 0]`, also appears first in the results from `reductions`. section 3.5.4

Without an initial value, `reduce` starts with the collection’s first item. On an empty or nil collection, it instead calls the reducing function with no arguments: `(reduce + nil)` returns `0`, while `(reduce / [])` raises an `ArityException`. section 3.5.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the accumulator and explains update order, initial values, and empty-input behavior.
Examples
Shows running sums of squares, word counts, and a running average with a vector accumulator.
What you can do after
Apply it via Clojure reduce and reductions to compute final or running results.
How it connects
Links accumulators to reducing functions, fold-left, reduce, and reductions.

Also explained in

Compare how 4 books explain accumulator →

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.