Sum and Product Types
The type checker of Part VI gives every Bridger expression a type, and a
tuple type describes data of one fixed shape. An arithmetic expression like 3 + 4 * 2 does not fit
one shape: it is a tree built from numbers, additions, and multiplications. To represent that tree
with only the types we have so far, the program below encodes each node as a three-element tuple
whose first element is a string tag. ("num", n, 0) is the number n, and its last element is an
unused filler. ("add", l, r) and ("mul", l, r) hold their two operands. value computes the
number a tree stands for, and Node in its signature is the type we would like e to have:
fn value(e: Node) -> Int =
if e.0 == "num" { e.1 }
else if e.0 == "add" { value(e.1) + value(e.2) }
else { value(e.1) * value(e.2) };
fn main() {
let e = ("add", ("num", 3, 0), ("mul", ("num", 4, 0), ("num", 2, 0)));
println(value(e));
println(value(("ad", ("num", 3, 0), ("num", 4, 0))));
println(value(("add", ("num", 3, 0), 4)));
}
If we run this program in the untyped evaluator of Part V, which ignores type annotations, it gets partway through:
11
12
It then halts with no such field 0 when e.0 tries to project a field from the bare integer 4.
The first line of output is right. In the second call the tag is misspelled "ad", so the if
chain falls through to its last branch and multiplies. In the third, a bare 4 sits where a subtree
belongs, and nothing objects until value reaches it.
With the type checker on, as it is from Part VI onward, the program never starts. The checker
reports that Node in the first line is an unknown type, and there is no type to write in its
place. ("num", 3, 0) has type (String, Int, Int). An
addition of two numbers has type (String, (String, Int, Int), (String, Int, Int)). Each deeper
tree has a longer type, yet value needs one parameter type that covers them all.
The program raises these questions:
- How does a type say “one of these shapes”? The list of shapes exists only in the
ifchain of one function. - How does each shape hold only what it needs? A number has one component, but its tuple has two, one of them a filler.
- How does a type refer to itself? An operand of an addition can be another addition.
- How can a tag be checked?
"ad"is a perfectly good string.
Where data declarations came from
Mathematical descriptions of data like this came before languages that could check them. John McCarthy’s “A Basis for a Mathematical Theory of Computation” (1963) built spaces of data out of sets with two operations. One was the Cartesian product. The other was the direct union: “The direct union A ⊕ B of the sets A and B is the union of two non-intersecting sets one of which is in 1-1 correspondence with A and the other with B.” He defined data recursively with equations such as , which describes a list, and gave each union a predicate to test which side a value came from. Peter Landin’s “The Mechanical Evaluation of Expressions” (1964) wrote similar definitions in structured English, beginning “An AE is either” and listing the alternatives, each with its parts. Both were descriptions of data for a reader, and a program had to honour them by its own discipline.
Programming languages took up the idea with varying amounts of enforcement. Tony Hoare’s “Notes on
Data Structuring” (1972) treated the
discriminated union as a basic way to build types, with a tag carried in every value and a
cardinality that is the sum of its alternatives’. Algol 68 had union modes, with a conformity
clause to select on a value’s actual mode. Pascal’s variant records made the tag field optional.
The ISO standard says that accessing a component of an
inactive variant is an error, and it defines an error as “A violation by a program of the
requirements of this International Standard that a processor is permitted to leave undetected.”
CLU, designed by Barbara Liskov’s group in the 1970s, had oneof types, which Liskov’s
history describes as “tagged unions”. A tagcase statement
selected on the tag and gave each arm the data stored under it. Hope, from Rod Burstall, David
MacQueen, and Don Sannella, joined these sums to recursion and polymorphism in a declaration a
programmer could write directly. Its 1980 paper
opens with the aim: “The user may freely define his own data types, without the need to devise a
complicated encoding in terms of low-level types.” Tagged tuples are such an encoding. Standard ML
adopted Hope’s datatypes, and Bridger’s type declaration
descends from that line.
Sums and products
A tuple type is a product. A value of type (Bool, Int) holds a Bool and an Int, one from
each component. A sum holds one of several alternatives, along with a tag that records which. A
value of a sum of Bool and Int holds a Bool or an Int.
The names come from counting. If a type has values, then
A pair chooses from both components independently, so the choices multiply. A sum chooses a tag and
then a value under that tag, so the choices add. The empty tuple type () has exactly one value and
behaves as 1 does in a product. Bool is a sum of two alternatives that carry nothing, .
| Type | Written as a sum of products | Values |
|---|---|---|
() | 1 | |
Bool | 2 | |
(Bool, Bool) | 4 | |
Option<Bool> | 3 | |
Option<Option<Bool>> | 4 | |
Result<Bool, Bool> | 4 |
Types built this way are called algebraic data types. The last row depends on the tags. Taken as
a set of values, the union of Bool with Bool is just Bool, with 2 elements. Result<Bool, Bool> has 4, because Ok(true) and Err(true) are different values. A sum is therefore a
disjoint union: the tag keeps the alternatives apart even when they hold the same type.
A sum can also mention itself. The tree of the opening example is
and the equation can be read as a recipe for building values level by level. Level 0 holds the numbers, which need no other trees. Level 1 adds every addition and multiplication of level 0 trees, level 2 every addition and multiplication of trees from levels 0 and 1, and so on. Each tree appears at some finite level, and the type is the union of the levels, the same construction Evaluating relations used to grow a relation’s facts round by round.
Bridger’s data types
A type declaration names a sum, and each alternative is a constructor with zero or more
argument types. The grammar is in Appendix B:
type_def ::= 'type' UpperIdent [ generics ] '='
[ '|' ] variant { '|' variant } ';' ;
variant ::= UpperIdent [ '(' type { ',' type } ')' ] ;
Each constructor’s arguments form a product, so a declaration is a sum of products. Here is the tree of the opening example, now with a type:
type Arith = Num(Int) | Add(Arith, Arith) | Mul(Arith, Arith);
fn main() {
let e = Add(Num(3), Mul(Num(4), Num(2)));
println(e);
println(e == Add(Num(3), Mul(Num(4), Num(2))));
println(Num(1) == Num(2));
}
This prints:
Add(Num(3), Mul(Num(4), Num(2)))
true
false
Arith lists every shape a tree can have. Num holds one component, while Add and Mul hold two
trees each. The declaration’s right-hand side mentions Arith directly, and every constructor name
is checked before the program runs.
A constructor with no arguments is written as a bare name, so a declaration of plain alternatives is an enumeration:
type Direction = North | East | South | West;
A declaration can take type parameters, exactly as a fn signature does in Function types and
polymorphism. This binary tree holds a T at each interior node:
type Tree<T> = Leaf | Node(Tree<T>, T, Tree<T>);
The prelude’s Option and Result are ordinary declarations of this form, and Appendix
C lists them as Bridger source:
type Option<T> = None | Some(T);
type Result<T, E> = Ok(T) | Err(E);
A constructor is a top-level name, so it can belong to only one type. Declaring Red in both
Color and Fruit is an error, which the checker reports at the second declaration. Since each
constructor belongs to one type, its name alone tells the checker which type it builds.
Evaluating a constructor
A constructor application builds a value tagged with the constructor’s name. Unlike a call, it runs no code. It evaluates its arguments left to right, threading the store and the relation database through them as every other rule does:
The result is a new form of value. Two constructor values are equal under ==
when their names match and their arguments are equal, position by position. For values of type
Option<Option<Int>>, None == Some(None) is false because their outer constructors differ.
Checking a constructor
In a declaration of , a constructor taking acts like a function from those types to :
For a generic declaration, the and the type arguments of come from the declaration with each type parameter consistently replaced, as in T-Inst.
The type checker now catches the opening program’s bugs, along with a wrong number of arguments:
Add(Num(3), "four") // type mismatch: expected Arith, found String
Add(Num(3)) // `Add` takes 2 argument(s), given 1
Ad(Num(3), Num(4)) // unknown constructor `Ad`
Like a generic function, a generic constructor is instantiated with fresh inference variables at
each use. The arguments can solve those variables, which makes Some(1) an Option<Int>. An
expected type can solve them as well, which is why let x: Option<Int> = Some("s") reports the
mismatch at "s". None has no arguments, so let n = None; with no other use is rejected by the
determination rule of A type checker and asks for an
annotation.
Although T-Con reads like a call, a constructor name is not a value in Bridger. A constructor is
always applied, so a bare Some is an application to zero arguments:
map([1, 2], Some) // `Some` takes 1 argument(s), given 0
map([1, 2], |x| Some(x)) // [Some(1), Some(2)]
Recursive types
Arith mentions itself with no extra syntax, and the top level’s order-free
declarations let two types mention each other as well. Rust’s Expr in
the AST chapter needed Box around each recursive field, because a Rust
value’s size has to be known and a tree’s depth is not. The reference interpreter’s constructor
value is a name and a shared, heap-allocated array of arguments, so that indirection is already
present for every Bridger value and the program never mentions it.
A declaration needs at least one constructor, but it does not need a level 0. The checker accepts
type Loop = Again(Loop);, and a program can never build a Loop, because every Again needs an
existing Loop first.
Building it
The parser delivers declarations and applications in the shapes given in The abstract syntax tree:
Type(Generics, Vec<Variant>), // type T<U> = C(U, …) | …
struct Variant { name: Name, fields: Vec<Ty>, span: Span } // C(T, …), or C
Ctor(Name, Vec<Expr>, Span), // constructor application: C(e, …)
and the runtime gives constructor values one more variant:
Ctor(Name, Rc<[Value]>), // C(v, …)
The evaluator’s arm follows E-Con: evaluate the arguments in order, then build the value. Because
the evaluator can also run unchecked programs, it has to compare the number of arguments with the
constructor’s declaration as well. A mismatch is a stuck ArityMismatch.
The checker’s arm looks the constructor up among the declarations, reports UnknownConstructor or
ArityMismatch if that fails, and makes fresh inference variables for the declaration’s type
parameters. If the context expects a type with the same head, unifying with it first means the
arguments are checked against what the context already knows, and the mismatch in the Some("s")
above lands on the argument.
The design space
Untagged unions
C’s union lays its alternatives over the same bytes and records nothing about which one was
stored. A C program that wants a sum pairs a union with an enum and keeps the two in agreement
by hand. Reading the wrong member reinterprets the bytes.
TypeScript’s union types, such as string | number, are untagged. That type is the set of strings
together with the set of numbers, and a program distinguishes them by testing the values at run
time. T | null | null collapses to T | null, so a TypeScript function
that returns T | null and is instantiated at a nullable T cannot separate “no result” from “a
result that is null”. Option<Option<T>> keeps those apart with its tags.
TypeScript programs often add tags themselves, with a literal field such as kind: "num", and the
checker narrows the type after a test of that field. The result is close to a Bridger sum, assembled
from record types.
Absence
Many languages let any reference be null. The check that a value is present is then a matter of
convention, and a missing check appears as a run-time failure at the dereference. Bridger has no
null: a function that might return nothing says so with Option<T>, and a value of type T is
present. Hoare, who added the null reference to ALGOL W, said in a 2009
talk:
“I call it my billion-dollar mistake. It was the invention of the null reference in 1965.” Kotlin
and Swift reach much the same guarantee by building optional types into the language, with special
syntax for testing and unwrapping. Bridger’s Option is written in the language itself.
Names and structure
Bridger’s sums are nominal: type A = X(Int); and type B = Y(Int); are unrelated types even
though they have the same shape, and a constructor belongs to one type. OCaml also offers
polymorphic variants, whose tags exist independently of any declaration, so a function can accept
“any type with at least these tags”. Because a tag no longer belongs to one declaration, the checker
cannot read a type off a constructor’s name as Bridger’s does, and the types it infers have to list
which tags a value may carry.
Constructors as functions
In ML, OCaml, and Haskell a constructor is a function, so map Some xs works. Bridger requires the
lambda. The rule leaves constructor expressions and patterns with one syntactic shape, at the cost
of a lambda wherever a constructor is passed along.
Sums in object-oriented languages
A class hierarchy can also describe “one of these shapes”, with a base class and one subclass per alternative. Java’s sealed interfaces and records make the set of alternatives closed, and Scala’s sealed traits and case classes have long served the same purpose. Part IX returns to how Bridger’s structs and traits relate to the sums of this part.
Further reading
Early definitions of data: Section 2.6 of McCarthy’s Basis defines products, direct unions, and recursive sets of data, then gives Lisp’s S-expressions in those terms. The sections of Hoare’s Notes on Data Structuring on Cartesian products, discriminated unions, and recursive data work through each with cardinalities and example programs.
Hope and ML: The Hope paper is eight pages
and includes data declarations and equational function definitions. MacQueen, Harper, and Reppy’s
“The History of Standard ML” (2020) traces how datatypes moved
from Hope into Standard ML and how they evolved there.
CLU: Liskov’s “A History of CLU” (1993) records the group’s design decisions and the state of the field when they were made.
Concept checks
How many values does each of these types have: (Bool, Option<Bool>), Result<(), Bool>, Option<Direction>?
, then , then . The count treats a product as multiplication and each constructor as one summand, with a constructor’s arguments contributing their own count.
Why does the opening example's misspelled tag run to completion, while Ad(Num(3), Num(4)) is rejected before the program starts?
"ad" is a value of type String, and any string is acceptable as the first element of a tuple.
The checker has no knowledge of which strings the if chain tests for. Ad is a name that must
resolve to a declared constructor, and the declaration is what makes the list of alternatives
available to the checker.
What level of the construction does Mul(Num(2), Add(Num(3), Num(4))) first appear at, and why does type Loop = Again(Loop); have no values?
Level 2. The numbers are at level 0, the Add is built from them at level 1, and the Mul needs
that Add. Loop has no alternative that can be built from nothing, so level 0 is empty, and every
later level is built from an empty set.
A language could give every type an implicit extra value null, or it could use a type like Option<T>. Compare what a function signature says in each, and what each costs at a use site.
With an implicit null, a parameter of type T might or might not hold a T, and the signature
gives no way to say which, so the check is left to convention and its absence appears at run time.
With Option<T> the signature states it, and a T is always present. The cost is that a use site
of an Option<T> must unwrap it, even where the programmer knows the value exists, and a value that
becomes optional changes the type at every place it flows through.