liveBook · Manning

Identity element

As explained in Functional Programming in Scala, Second Edition

Identity is the property that an operation has an element whose combination with another element leaves that element unchanged.

An identity element is a value that leaves another value unchanged when combined with it. For an operation combine, an identity empty satisfies combine(x, empty) == x and combine(empty, x) == x. The operation therefore has a neutral value on both sides. section 10.1

Common operations use different identity elements:

  • String concatenation uses the empty string: s + "" and "" + s both produce s. section 10.1
  • Integer addition uses 0, while integer multiplication uses 1. section 10.1
  • Boolean conjunction uses true, Boolean disjunction uses false, and list concatenation uses Nil. section 10.1 section 10.9
trait Monoid[A]:
  def combine(a1: A, a2: A): A    #1
  def empty: A                    #2

A monoid records an associative combine operation together with its identity value, named empty. This interface separates the algebraic structure from any particular data type. section 10.1 section 10.9

Identity is one of the two monoid laws; the other is associativity. Together they make generic combination possible, including folding a list into one value with combineAll or mapping and combining with foldMap. The same pattern appears in monads, where unit acts as the identity for composition: composing with unit leaves a computation unchanged. section 10.9 section 11.4.3

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines two-sided identity laws and connects them to monoids and monads without developing their implementations in depth.
Examples
Uses empty strings, zero, one, Boolean constants, Nil, monoid traits, and monadic unit as examples.
What it assumes
Assumes familiarity with binary operations and equality while introducing monoid and monad identity laws through concrete examples.
What you can do after
Evaluate/understand whether an operation has a neutral value and recognize its role in generic algebraic interfaces.
How it connects
Connects identity elements with monoids, associativity, monads, unit, combineAll, and foldMap.

Also explained in

Compare how 5 books explain identity element →

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.