Learning path

Full curriculum

Full curriculum

Unit content

Product and sum types

Two fundamental ways to combine types are products and sums.

A product type $A\times B$ contains both an $A$ and a $B$. A pair

$$(a,b):A\times B$$

can be projected to recover either component. Records and tuples are practical forms of products.

A sum type $A+B$ contains either an $A$ or a $B$, together with information identifying which alternative is present. Constructors can be written

$$\operatorname{inl}(a):A+B$$

and

$$\operatorname{inr}(b):A+B.$$

Using a sum safely requires considering both cases. For example, a result type

$$\text{Int}+\text{Error}$$

makes success and failure explicit alternatives rather than encoding failure in an unrelated sentinel value.

Products correspond to “and”: a value contains an $A$ and a $B$. Sums correspond to “or”: a value contains an $A$ or a $B$.

These two constructors form the basis of tuples, records, optional values, tagged unions and many algebraic data types. Their structure also determines how programs consume them: projection eliminates products, while case analysis eliminates sums.