liveBook · Manning

Monoid

As explained in Clojure: The Essential Reference

An algebraic monoid is a set equipped with an associative binary operation and an identity element.

A monoid combines a binary operation with an identity value. In Clojure's reducers, r/monoid adapts a two-argument reducing function so it also supplies the zero-argument initial value required by fold. section 7.1.3

Use r/monoid when a fold needs a reducing function with both arities:

  • Provide op as a function accepting two arguments. section 7.1.3
  • Provide ctor as a zero-argument function returning the initial value; wrap constants with constantly. section 7.1.3
  • Receive a function callable with either zero arguments or two arguments; the latter are passed to op in order. section 7.1.3

Concatenating with fold

(require '[clojure.core.reducers :as r]) (r/fold (r/monoid str (constantly "Concatenate ")) ["th" "is " "str" "ing"]) ;; "Concatenate this string" Passing a value such as 0 instead of (constantly 0) causes a ClassCastException because ctor must be callable. section 7.1.3

(r/fold (r/monoid merge (constantly {}))  ; #1
        (fn [m k v] (assoc m k (str v)))
        (zipmap (range 10) (range 10)))

;; {0 "0", 7 "7", 1 "1", 4 "4",
    6 "6", 3 "3", 2 "2", 9 "9",
    5 "5", 8 "8"}

Browse a map-fold example that uses merge with an empty-map constructor and combines transformed entries. section 7.1.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines identity and associativity, then details arity, contracts, return behavior, and common constructor errors.
Examples
Demonstrates string concatenation, map merging, numeric addition, and composed reducer transformations.
What it assumes
Assumes familiarity with Clojure functions, reduce, and fold while introducing identity and associativity through numeric examples.
What you can do after
Apply r/monoid to build fold combiners with correct zero-argument initialization and two-argument reduction.
How it connects
Connects monoids with reducers, fold, reducing functions, associative operations, and identity elements.

Also explained in

Compare how 3 books explain Monoid →

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.