liveBook · Manning

Reducing function

As explained in Clojure: The Essential Reference

A reducing function is a function that combines an accumulator with the next element of a collection during a reduction.

A reducing function combines an accumulator—the result so far—with the next collection item. Clojure’s `reduce` calls it repeatedly from left to right and returns the final accumulator. The result need not be a number: it can be a map built up as items arrive. section 3.5.4

Sum squares

`(reduce + (map #(* % %) (range 5)))` returns `30`. To see each result so far, use `(reductions + (map #(* % %) (range 5)))`, which returns `(0 1 5 14 30)`. section 3.5.4

With an initial value, that value becomes the first accumulator; an empty collection returns it unchanged. Without one, a single item is returned unchanged, while an empty or nil collection calls the function with zero arguments. Thus `(reduce + nil)` returns `0`, but `(reduce / [])` throws an `ArityException`. section 3.5.4

(defn count-occurrences [coll]
  (->> coll
       (map #(vector % 1))                       ; #1
       (reduce (fn [m [k cnt]]                   ; #2
         (assoc m k (+ cnt (get m k 0)))) {})))  ; #3

(defn word-count [s]
  (count-occurrences (.split #"\s+" s)))

(word-count "To all things, all men, all of the women and children")

;;{"To" 1
;; "all" 3
;; "and" 1
;; "children" 1
;; "men," 1
;; "of" 1
;; "the" 1
;; "things," 1
;; "women" 1}

A word-count reduction uses a map as its accumulator, updating each word’s count. For this particular task, `frequencies` is the shorter alternative. section 3.5.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the accumulator and two-argument function, then covers initial values, empty collections, arity errors, and non-scalar results.
Examples
Uses sums of squares, word counts accumulated in a map, and running averages.
What it assumes
Assumes basic Clojure function and collection syntax while defining the accumulator and reducing-function vocabulary.
What you can do after
Apply it via Clojure’s `reduce` to combine values or build a map, choosing `reductions` when intermediate results matter.
How it connects
Links reducing functions to fold-left, `reductions`, `reduced`, and `frequencies`.

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.