A monoid combines a type A with an associative binary operation, combine, and an identity value, empty. Associativity permits regrouping without changing the result, while identity leaves any value unchanged. The structure is purely algebraic: its instances need share only these operations and laws. section 10.1
trait Monoid[A]: def combine(a1: A, a2: A): A #1 def empty: A #2
The Scala interface makes the abstraction concrete: combine accepts two values of the same type, and empty supplies the identity. section 10.1
Common monoids differ in their values and operations while obeying the same laws:
- String concatenation uses the empty string as identity. section 10.1
- Integer addition uses 0; integer multiplication uses 1. section 10.1
- Boolean conjunction uses true, disjunction uses false, and list concatenation uses Nil. section 10.1
Monoids turn folding into a generic operation. combineAll reduces a list using empty and combine; foldMap first maps elements into a monoidal type and then combines them. Because associativity makes left and right grouping equivalent, folds can also support parallel computation. Product monoids combine several calculations in one traversal, such as counting and summing a list to compute its mean. section 10.2 section 10.7.2 section 10.8


