Part IA Michaelmas Term
Enumeration Types
Declaring a new type
OCaml’s type declaration introduces new types beyond the built-in ones. An enumeration type is a type defined by listing its possible values (called constructors):
type vehicle = Bike | Motorbike | Car | Lorry
This declaration:
- Creates a new type called
vehicle. - Creates four new constants (
Bike,Motorbike,Car,Lorry) of that type. - The constructors serve both as values and as patterns for pattern matching.
Pattern matching on constructors
Once declared, the new type behaves like a built-in type:
let wheels = function
| Bike -> 2
| Motorbike -> 2
| Car -> 4
| Lorry -> 18
The type of wheels is vehicle -> int. The compiler checks that all cases are covered and warns about missing or redundant patterns.
Why not use integers or strings?
| Approach | Problem |
|---|---|
| Integers (0, 1, 2, 3) | Code is hard to read; adding a new constructor may shift all numbers |
| Strings (“Bike”, “Car”, …) | Comparisons are slow; typos like “MOtorbike” are silent bugs |
| Enumeration type | Compiler catches missing cases and typos; values are distinct types |
The compiler chooses the internal integer representation automatically. Type safety prevents confusion between different enumeration types: Bike and Red (from a colour type) are distinct and cannot be accidentally interchanged.
Most programming languages support enumeration types. Common examples include days of the week, colours, and states in a state machine.