Monoid

On this page 7

A monoid is an algebraic structure consisting of a set of values, a binary operation that combines two values into one, and an identity element that leaves any value unchanged when combined with it. The operation must be associative, so the grouping of combinations never changes the result. In functional programming, monoids describe anything that can be accumulated, merged or reduced, from numbers and strings to logs, statistics and configuration.

The concept comes from abstract algebra, but in Programming it is valued for practical reasons: a monoid guarantees that a fold over any collection is well defined, including an empty one, and that the work can be split across threads or machines without changing the answer.

The two monoid laws

A type forms a monoid when its combining operation and identity satisfy exactly two laws. These laws are not checked by most compilers, so the programmer is responsible for them, often with property-based tests.

LawFormal statementPractical meaning
Associativity(a • b) • c = a • (b • c)Grouping does not matter, so work can be split
Left identitye • a = aCombining with the empty value changes nothing
Right identitya • e = aThe empty value is neutral on both sides
Laws every monoid must satisfy

Associativity is not the same as commutativity. String concatenation is associative but not commutative, because “ab” followed by “c” equals “a” followed by “bc”, while “ab” and “ba” differ. A monoid whose operation is also commutative is called a commutative monoid, and it additionally allows elements to be combined in any order.

A structure with an associative operation but no identity element is a semigroup. Non-empty lists under concatenation and the maximum of integers without a lower bound are typical semigroups. Adding an identity, for example by wrapping values in an option type, turns any semigroup into a monoid.

Common monoids in everyday code

Many familiar operations are monoids, and the same set of values can form several monoids with different operations. Integers form one monoid under addition and another under multiplication, which is why libraries often wrap the type to select the intended instance.

ValuesOperationIdentity element
Numbers under additiona + b0
Numbers under multiplicationa × b1
StringsConcatenationEmpty string
ListsConcatenationEmpty list
Booleans under conjunctiona and btrue
Booleans under disjunctiona or bfalse
Maps with monoidal valuesKey-wise mergeEmpty map
Functions from a type to itselfFunction compositionIdentity function
Typical monoids and their identity elements

The last row shows that monoids are not limited to data: endofunctions under composition form a monoid, which connects the concept directly to function composition and point-free style.

Monoids as type classes and interfaces

Functional languages usually express monoids as a type class or interface with two members: the identity value and the combine function. Haskell defines Monoid with mempty and mappend, written as the operator <> and inherited from Semigroup. Scala libraries such as Cats provide Monoid with empty and combine, and similar abstractions exist in PureScript, F# libraries and TypeScript functional toolkits.

Generic functions can then work with any monoid without knowing the concrete type. A single function such as mconcat or combineAll reduces a list of numbers, strings or maps, choosing the right behavior from the instance. This is the main engineering benefit: one well-tested reduction replaces many hand-written loops.

Monoids also compose. If A and B are monoids, the pair of A and B is a monoid with component-wise combination, and a function returning a monoid is itself a monoid under point-wise combination. Complex aggregations can therefore be built from small, lawful parts.

Monoids sit in a hierarchy of algebraic abstractions that functional programmers meet regularly. Knowing where each one applies prevents choosing a structure that is too weak or too demanding.

AbstractionRequiresTypical use
SemigroupAssociative operationCombining non-empty data
MonoidAssociative operation and identityFolding any collection, including empty ones
Commutative monoidMonoid plus order independenceDistributed counters and set unions
GroupMonoid plus inversesUndoable changes, such as subtraction
MonadLawful sequencing of computationsChaining effects such as failure or state
Monoid and neighboring abstractions

The phrase that a monad is a monoid in the category of endofunctors is mathematically accurate but describes a different level: a monad combines computations, while an ordinary monoid combines values. The two should not be confused when designing an interface.

Why monoids matter for folds and parallelism

A fold reduces a collection to one value, and a monoid makes that reduction safe and flexible. The identity element supplies the starting value, so folding an empty collection returns a meaningful result instead of failing. Associativity allows a left fold, right fold or balanced tree reduction to produce the same answer.

This property underpins parallel and distributed aggregation. MapReduce-style systems split data into chunks, reduce each chunk independently and merge the partial results. Streaming frameworks use the same idea to update running aggregates incrementally. When the operation is also commutative, partial results can arrive in any order without coordination.

  • Floating-point addition is not strictly associative, so parallel sums can differ in the last digits; use compensated summation or accept a tolerance.
  • Average is not a monoid on its own; store sum and count as a pair and divide at the end.
  • Choosing the wrong identity, such as zero for a maximum over negative numbers, silently corrupts results.
  • Unlawful instances compile normally but break parallel code in subtle ways, so laws should be tested.

The short version

A monoid is any kind of thing you can merge two at a time, with a neutral starting point. Adding numbers starting from zero is the simplest case, and joining pieces of text starting from blank text is another.

Because the merging does not care how the pieces are grouped, a big job can be shared among many workers. Each worker merges its own pile, and the piles are merged at the end with the same result as doing everything alone.

Where it makes a difference

An analytics team processes about 2 billion web events per day across 200 worker machines. For each page they need the visit count, the total time spent, the longest session and the set of referring sites. They define one summary record whose fields are each monoids: addition for counts and time, maximum with an identity of zero for session length, and set union for referrers.

Because the record is a monoid built from lawful parts, each worker summarizes its share of events independently and the coordinator merges 200 partial summaries in any grouping. Adding a new hourly roll-up later required no change to the merge logic, and an empty hour simply produced the identity record instead of an error. Average session time is derived at the end from total time and visit count, which keeps every stored field associative.