Some answers we would all give:
int — a set of numbers?int32 — the same, but exactly \(2^{32}\) of them?struct — several values glued together?class — values with code attached?Each describes one aspect. The question returns in four later sessions:
| S3 · today | how a datatype organises its values |
| S8 | a type as a protocol |
| S10 | what a type claims about a value |
| S12 | what a type hides |
| S13 | a type as a relation |
In everyday use, “object” bundles several design decisions. Five of them, each treated on its own day:
| bundled into “object” | actually a separate axis | |
|---|---|---|
| mutable fields, identity | state vs. persistence | S2, S7 |
inheritance, extends | subtyping | S11 |
| classes | classes vs. prototypes (Self, JS) | today, one slide |
declared implements | nominal vs. structural typing (Java vs. Go) | S11 |
| static types | Smalltalk has none | S10 |
Last week we read two of them without the name — and used the first in the type of pop:
type 'a option = None | Some of 'a
type 'a list = [] | (::) of 'a * 'a list
val pop : 'a t -> ('a * 'a t) option
(* the value and the new version — or nothing *)
Every value is built from a closed list of shapes, and taken apart the same way.
A set of integers. Four operations, and nothing else:
empty // the set with no elements
insert(s, n) // the set s, with n added
contains(s, x) // is x in s?
union(s, t) // every element of s, or of t
Client code uses only these four names.
Two implementations follow. The client cannot tell them apart — until the interface grows.
A set is an array: the elements it holds, and nothing else.
Every operation inspects* the array.
union1 inspects both of its arguments.
* inspect: read the representation directly — here as an array; in OCaml, as a constructor and its arguments.
A set is a function that answers one question: is x inside?
Every operation calls* the set. contains2 is just the call.
* call: use a value only through the interface it exposes, learning nothing about how it is made.
union2 can do nothing with s and t except call them. There is no inside.
const s3 = insert1(empty1, 3)
// = [3]
const s35 = insert1(s3, 5)
// = [3, 5]
Each step produces data: an array anyone may inspect.
const s3 = insert2(empty2, 3)
// = x => x === 3 || empty2(x)
const s35 = insert2(s3, 5)
// = y => y === 5 || s3(y)
Each step produces a closure*. s35 holds s3; nothing runs until someone calls it.
* closure: a function together with the bindings it captured where it was defined — here n and the previous set.
s35 are chains of length two: [3, 5], and a function holding 5 and s3, which holds 3 and empty2. Same shape — and, from the operations’ side, one can be inspected while the other can only be called.
Nothing so far tells the two apart. But what if we extend the interface with
isEmpty
One line. Nothing else is touched.
const isEmpty2 = s => ???
No call tells whether a function ever answers true. So a set must carry a second function:
empty, insert and union, is rebuilt this way.equalconst union1 = (s, t) =>
[...s, ...t.filter(x => !s.includes(x))];
const equal1 = (s, t) =>
s.length === t.length &&
s.every(x => t.includes(x));
union1 reads both arrays and merges them; equal1 reads both and compares them.
const union2 = (s, t) => x => s(x) || t(x);
const equal2 = (s, t) => ???
union2 and equal2 can only call s and t. Enough for union —
not enough for equal: no finite number of calls decides whether two functions agree on every input.
x and combine the answers.No array holds the even numbers. As data, the evens must be a second kind of set, told apart from the first by a tag:
{ kind: 'finite', xs: [3, 5] } // as before
{ kind: 'evens' } // no array
— and every operation now begins by reading the tag:
const contains1 = (s, x) =>
s.kind === 'evens' ? x % 2 === 0
: s.xs.includes(x);
const isEmpty1 = s =>
s.kind === 'evens' ? false
: s.xs.length === 0;
equal1 gains one case per pair of kinds.
One record, and it holds every even number. The other makers and every client stay as they are.
But what is the union of {3, 5} and the evens? For Way 2, union2b answers as always. For Way 1 —
Problem: in Way 1, {3, 5} ∪ evens is neither finite nor evens.Solution: as before, add a new kind with a tag:
{ kind: 'finite', xs: [3, 5] } // as before
{ kind: 'evens' } // as before
{ kind: 'union', s, t } // both sets, kept
const union1 = (s, t) =>
s.kind === 'finite' && t.kind === 'finite'
? finite(merge(s.xs, t.xs))
: { kind: 'union', s, t };
Every operation that reads a set needs a union clause. contains1:
function contains1(s, x) {
if (s.kind === 'finite') return s.xs.includes(x);
if (s.kind === 'evens') return x % 2 === 0;
if (s.kind === 'union')
return contains1(s.s, x) || contains1(s.t, x);
}
union2b already builds the set, as a function: const union2b = (s, t) => ({ contains: x => s.contains(x) || t.contains(x), isEmpty: () => s.isEmpty() && t.isEmpty() });equal1 for new representation. Do you run into a problem comparing {3, 5} ∪ evens and evens ∪ {3, 5}? | Way 1 — a set is data | Way 2 — a set is a function | |
|---|---|---|
| a new operation | one new function | every maker rebuilt |
| an operation on two sets | inspect both | call both — no comparison |
| a new kind of set | every operation changed | one new record |
Two ways of implementing one interface. Neither is a language feature — we used arrays, arrow functions and records. The names come next.
| what we built | what it is called |
|---|---|
| Way 1 — a value is data; operations inspect it | algebraic data types |
| Way 2 — a value is a function; operations call it | objects |
Both are older than the languages we write them in. Reynolds (1975) called them user-defined types and procedural data structures — “complementary approaches to data abstraction”.
type note = C | D | E | F | G | A | B
let semitones n = match n with
| C -> 0 | D -> 2 | E -> 4 | F -> 5 | G -> 7 | A -> 9 | B -> 11
Reading rule: | is or. A note is C, or D, or …
The constructors are values we invent. C is not 0; nothing is inside it. It is a tag, as kind: 'evens' was for the set — but one of exactly seven values of a new type, note, each distinct from the others by construction.
enum, was static final int C = 0, D = 2, …C + D compiles, and 7 is accepted wherever a note is expected. A variant type allows neither.type pitch = { note : note; octave : int }
type duration = Whole | Half | Quarter | Eighth
type symbol = Note of duration * pitch | Rest of duration
pitch is a product type: each of its values holds every field.symbol is a sum type: each of its values is exactly one alternative — a Note carrying a duration and a pitch, or a Rest carrying a duration. That is what of reads as.A Rest carries no pitch: no field is left empty or set to null — a rest with a pitch cannot be written at all.
let beats s = match s with
| Note (d, _) | Rest d -> beats_of d
unit | \(1\) |
bool | \(2\) |
note | \(7\) |
duration | \(4\) |
pitch = note × int | \(7 \cdot |\mathrm{int}|\) |
symbol = duration × pitch + duration | \(4 \cdot 7 \cdot |\mathrm{int}| + 4\) |
\[|A \times B| = |A|\cdot|B| \quad\; |A + B| = |A| + |B|\]
The laws of + and × hold as isomorphisms of types, with a conversion function each way:
\[A \times (B + C) \;\cong\; A\times B + A\times C\]
struct symbol {
int tag; /* 0 = note, 1 = rest */
int duration, note, octave;
};
\(2^{128}\) states, four 32-bit ints. Most mean nothing: a rest with a pitch; a tag of 7.
type symbol =
| Note of duration * pitch
| Rest of duration
(* two shapes, nothing else *)
\(4\cdot 7\cdot|\mathrm{int}| + 4\) states. Each means something.
option | absence as one explicit case: None | Some of 'a has one more value than 'a, and every match must handle it. |
null | absence added to every reference type at once and recorded in none: no match is required, but the missing case surfaces at runtime as a NullPointerException. |
type 'a list = [] | (::) of 'a * 'a list
type set = Empty | Insert of int * set (* slide 6, as a type *)
let rec contains s x = match s with
| Empty -> false
| Insert (n, rest) -> n = x || contains rest x
Its equation, solved: \(L = 1 + aL \;\Rightarrow\; L = \tfrac{1}{1 - a} = 1 + a + a^2 + a^3 + \cdots\)
A list is empty, or one element, or two, or three … — a tuple of some length, one shape for each length.
The set we wrote as an array on slide 6 is now a type. The closed list of shapes — Empty, Insert — is written down where the compiler can read it.
length : 'a list -> int (* an ordinary function *)
Note : duration * pitch -> symbol (* a constructor *)
An ordinary function may lose information: from length xs we cannot recover xs; many lists share one length.
A constructor loses no information, and comes with three guarantees:
| injective | different carried values give different values |
| disjoint | different constructors never build the same value |
| exhaustive | every value of the type came from some constructor |
* Unlike Java’s constructors, these run no code and can be taken apart: a tag with a payload.
let s = Note (d, p) (* forwards: build *)
match s with Note (d, p) -> … (* backwards: recover d and p *)
(d, p) ↦ Note (d, p).match goes from the value back to the carried values: Note (d, p) ↦ (d, p).f x for an arbitrary f: there is no inverse to run.match covers every shape, and no case is unreachable.| 1970s | Pascal variant records; C union with a tag field — the list of shapes is a convention, unchecked |
| 1977 | NPL (Burstall): types built from constructors, and patterns on them |
| 1980 | Hope (Burstall, MacQueen, Sannella): the closed declaration — type and constructors together |
| 1984 → | Standard ML, then OCaml and Haskell: the ML family makes them the default |
| 2014 → | Swift enums, Rust enums, Kotlin sealed classes, TypeScript discriminated unions |
| 2021 → | Python 3.10 match; Java 17 sealed, Java 21 pattern switch |
“Algebraic” also names the mathematics: the values of the type are exactly the terms built from its constructors, nothing more and nothing identified — the initial algebra of its constructors (Goguen, Thatcher, Wagner, Wright, 1977).
OCamltype set =
< contains : int -> bool; is_empty : bool >
let empty : set = object
method contains _ = false
method is_empty = true
end
let insert (s : set) n : set = object
method contains x = x = n || s#contains x
method is_empty = false
end
type set is the interface of a set — extension 1’s record of operations, as a type — and under it two kinds of set, empty and insert*.
In the Way 1 type they were the constructors Empty and Insert; here the type lists only operations, and the kinds live in the code.
match on a set: nothing at compile time says how many kinds exist, or which one we hold.* object … end builds one object and # calls a method. No class is involved. All four kinds: demos/set_way2.ml.
Javaabstract class Set {
abstract boolean contains(int x);
abstract boolean isEmpty();
}
class Empty extends Set {
boolean contains(int x) { return false; }
boolean isEmpty() { return true; }
}
class Insert extends Set {
private final Set s; private final int n;
Insert(Set s, int n)
{ this.s = s; this.n = n; }
boolean contains(int x)
{ return x == n || s.contains(x); }
boolean isEmpty() { return false; }
}
The abstract class is the interface*; each subclass is one kind, with its own operations.
The fields are private**: from a client’s side, a Set is only what its methods answer.
* A Java interface says the same, without instance fields. All four kinds: demos/SetWay2.java.
** private: no client reads the field. final: assigned once, in the constructor — a set never changes after it is made.
A new kind is one more class:
Javaclass Evens extends Set {
boolean contains(int x) { return x % 2 == 0; }
boolean isEmpty() { return false; }
}
Set, Empty, Insert and every client stay as they are:
Set s = new Insert(new Insert(new Empty(), 3), 5);
s.contains(4);
Which contains runs is decided by the object s holds, at run time — three calls down the chain, none visible to the caller.
Nothing so far needed a class. In everyday languages, a class bundles several jobs:
new makes objectsSet in signaturesSet.emptyLanguages disagree on which to bundle, and on whether to have a class at all:
Javapublic boolean equals(Object o) {
return o instanceof Insert i && i.n == n && i.s.equals(s);
}
All six jobs in one box. Privacy is per class, not per object: equals reads another object’s n. The static methods of a class are the operations of an abstract data type.
s := Insert new.
x > 0 ifTrue: [ 'positive' ] ifFalse: [ 'not' ]
A class is itself an object, and new is a message to it. Even if is a message — a method call the receiver chooses: ifTrue:ifFalse: is sent to the boolean with two blocks (closures) as arguments; true runs the first, false the second.
const empty = { contains: x => false, kind: 'set' };
const evens = Object.create(empty); // its prototype is empty
evens.contains = x => x % 2 === 0; // its own; evens.kind is still found on empty
No class underneath: objects are made from objects. The prototype is another object, asked for any property the new one lacks. The class syntax of 2015 does not replace this: a method is still found through the prototype.
let empty = object method contains _ = false end
(* empty : < contains : 'a -> bool > *)
An object without a class. Its type is the list of its methods. A class, when we want one, is a recipe for making objects — a factory and code sharing, nothing more.
type Reader interface { Read(p []byte) (int, error) }
No classes and no implements: any value with a Read method is a Reader. The interface is satisfied by shape — session 11. Same way, different amount of declaration.
Both ways hide how an operation works: a client calls contains and gets an answer, never seeing the body — the array scan, or the chain of calls. Any function does this much. What each way adds differs:
| [ADT] | Way 1, behind a wall we will build in session 12. The representation type is hidden: behind an .mli, as session 2’s stack, type t shows no constructors, so no client can match on a set or build one by hand. Cook calls this type abstraction. Only a compiler can enforce it. |
| [Objects] | Way 2, as it stands. Nothing is hidden at the type level: the interface type is public. What is hidden is the environment of one closure — this s, this n — and it is hidden by being a function: nothing but a call can reach in. Cook calls this procedural abstraction: a procedure’s wall, with the data inside. |
| abstract data type | object | |
|---|---|---|
| what is abstracted | the representation type | the procedures in a value |
| operation bodies | hidden | hidden |
| representation | one, hidden | none in the interface |
| an operation is written | once, for every value | by each value, for itself |
| sees another value’s inside | yes — union1, equal1 | no — union2; no equal2 |
| implementations | one per type; two do not mix | any number, one type; they mix |
Reynolds (1975) saw the two as complementary; Cook (2009) gave the table its rows.
t runs the same contains, and its match chooses the kind — the value does not.contains | isEmpty | union | equal | |
|---|---|---|---|---|
| Empty | ✓ | ✓ | ✓ | ✓ |
| Insert | ✓ | ✓ | ✓ | ✓ |
| Evens | ✓ | ✓ | ✓ | ✓ |
| Union | ✓ | ✓ | ✓ | ✓ |
Algebraic data types (Way 1): one function per operation, every kind inside it — a column at a time.
One more operation is one more column, equal included: a function inspects both sets, through a normal form.
Objects (Way 2): one class per kind, every operation inside it — a row at a time.
One more kind is one more row, Union included. equal gets no row: in general, a row cannot inspect another.
abstract class Set { … }
class Empty extends Set { … }
class Insert extends Set { … }
class Evens extends Set { … }
class Union extends Set { … }
Rows. The part before, as written.
sealed, records, switchJavasealed interface Shape
permits Circle, Square, Tri {}
record Circle(double r) implements Shape {}
record Square(double s) implements Shape {}
record Tri(double b, double h) implements Shape {}
static double area(Shape sh) {
return switch (sh) {
case Circle c -> Math.PI * c.r() * c.r();
case Square s -> s.s() * s.s();
};
}
permits is |, record is of, switch is match. Java required a quarter of a century, and three additions to the language, before it could express the second form directly, with the compiler checking the cases. That delay is the measure of its default.One case left out of a match, on purpose. Three compilers, three answers:
| OCaml | Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: Repeat (_, _) |
| Java 21+ | A.java:10: error: the switch expression does not cover all possible input values |
| Python 3.10+ | square: 9 triangle: None |
OCaml warns and names a missing value. Java refuses to compile. Python runs, and the missing case becomes a None that travels on.
OCaml: the lab’s melody with Repeat added and no match updated. Java, Python: Tri left out of area.
Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: Repeat (_, _)
Does every operation handle every kind?
B.java:10: error: Evens is not abstract and does not override abstract method isEmpty() in Set
Does every kind provide every operation?
permits list, or the abstract class.An instanceof chain is not a match: nothing checks it — hence the visitor.
Javainterface Visitor<R> {
R onEmpty();
R onInsert(Set s, int n);
}
abstract class Set {
abstract <R> R accept(Visitor<R> v);
}
class Empty extends Set {
<R> R accept(Visitor<R> v)
{ return v.onEmpty(); }
}
class Insert extends Set {
<R> R accept(Visitor<R> v)
{ return v.onInsert(s, n); }
}
isEmpty(new Insert(new Empty(), 3)) // v: the visitor
s.accept(v) → s is an Insert: Insert.accept
v.onInsert(s, 3) → the arm for Insert
= false → the set chose the arm
Way 1 would write one match, an arm per kind. Java has none; we build it by hand:
onEmpty and onInsert — the armsaccept: each kind’s one new method; it calls its own arm and hands over what it carriess.accept(v) dispatches twice: the set picks accept, accept picks the arm. The set chose the arm, not the caller.Way 1’s trade, cost included: isEmpty is one visitor, written outside; a new kind needs onEvens in every visitor.
Widget; plug-ins add kinds it never seesOptionMuch “object” code is data with getters — the shape that record and sealed were added to Java to fix.
| language | default | the other way |
|---|---|---|
| OCaml | Way 1 | object … end — rarely used |
| Rust, Swift, Haskell | Way 1 | dyn Trait, protocols, type classes |
| Java | Way 2 | sealed + record + switch, since 2021 |
| Smalltalk | Way 2 only | no static list of kinds — session 10 |
| Python, JavaScript | Way 2, untyped | Python’s match, unchecked; a kind field by hand |
| Go | Way 2, by shape | a type switch, unchecked for missing cases |
This session answered what is a datatype? by how it organises its values: by construction, or by behaviour. Four later sessions answer it again:
| S8 | a type as a protocol: which messages, in which order — session types |
| S10 | what a type claims about a value: a type as a proof; Smalltalk’s one big sum |
| S12 | what a type hides: abstract data types. Way 1 behind a wall; session 2’s .mli returns |
| S13 | a type as a relation: tables, queries; a query plan is a tree — a Way 1 program |
melody typetype melody =
| Note of duration * pitch
| Rest of duration
| Seq of melody * melody (* after *)
| Par of melody * melody (* together *)
Every function in the lab is one match on this type. melody.ml has the holes; dune exec ./main.exe reports each one.
| A | count_notes, length_in_beats: Seq adds, Par takes the maximum |
| B | to_events, then a .wav of Bach’s Invention in C; add Repeat, follow the warnings |
| C | transpose_octave, pretty, retrograde, simplify |
| read | CS3110 chapter 3: sections 3.1, 3.5, 3.6, 3.8, 3.11, 3.12 |