liveBook · Manning

Monoid

As explained in Functional Programming in Scala, Second Edition

A Monoid is an algebraic structure with an associative binary operation and an identity element.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines operations and laws, implements list folds and products, and stops short of broader algebraic structures.
Examples
Uses strings, lists, integers, booleans, options, endofunctions, and a fused count-and-sum mean calculation.
What it assumes
Assumes familiarity with Scala lists and folds while developing algebraic reasoning, laws, typeclasses, and given instances.
What you can do after
Build it from scratch by defining lawful instances and generic combineAll, foldMap, and product operations.
How it connects
Connects algebraic laws with typeclasses, foldLeft, foldRight, foldMap, Foldable, and parallel computation.

Also explained in

Compare how 3 books explain Monoid →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.