liveBook · Manning

Associativity

As explained in Learn Haskell by Example

An associative function is a binary operation whose grouping does not affect the result.

Associativity means that regrouping a sequence of applications does not change its result: a <> (b <> c) == (a <> b) <> c. The operands remain in the same order; only the grouping changes. section 7.3.1

Appending three CSV values illustrates the property. Both appendCsv a (appendCsv b c) and appendCsv (appendCsv a b) c produce the same result when appendCsv is associative. Haskell does not prove this law, so the implementer must verify it. section 7.3.1

In Haskell, associativity supports reusable combination APIs:

  • Semigroup provides the binary associative operation <> for a type. section 7.3.1 section 7.5
  • Monoid extends Semigroup with mempty, a neutral element, and mconcat for combining a list of values. section 7.3.1
  • Associativity does not imply commutativity: changing a <> b to b <> a can change the required result. section 7.3.1

How Learn Haskell by Example covers it

How deep it goes
Defines the equality law, distinguishes grouping from operand order, and notes that the compiler does not verify it.
Examples
Uses CSV values, lists, and strings to demonstrate associative combination with <> and mconcat.
What you can do after
Build it from scratch by implementing an associative append operation and checking its Semigroup law.
How it connects
Connects associativity to Semigroup, Monoid, binary operations, and CSV combination.

Also explained in

Compare how 5 books explain associativity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.