A 2D coordinate treats its x-value and y-value as a single pair. Bundling several values together like this gives a product type, whereas holding one of several alternatives, such as pending, paid, or failed for a payment, gives a sum type. Here we declare coordinates with structure and payment states with inductive.
Start with an empty DataTypes.lean and run the coordinate example with lean DataTypes.lean. Append the payment example to the same file and run it again; its results follow the coordinate output.
1. Bundling Multiple Fields with structure
We create a coordinate type with structure Point where and list its fields x : Int and y : Int underneath where. Packing both numbers into one value lets you pass the entire coordinate to a function at once and read p.x or p.y only when a calculation needs them. Adding deriving Repr at the end generates a display representation so #eval moved prints both fields together.12
Repr tells Lean how to turn a value into printable text. With deriving, Lean builds that formatter straight from the fields of the new type, so you can inspect a point without writing a printing function by hand.
Each symbol in the display below maps to one part of the structure. The cross symbol in denotes the set of all ordered pairs of two integers (the Cartesian product), and the wavy equals sign is the isomorphism symbol meaning that a Point structure and an integer pair correspond one-to-one with identical information.
Also, and (where the Greek letter “pi” stands for projection) are the projection functions that extract the -component and -component from a pair, while the vertical bars denote the absolute value without its sign.
So manhattan computes the Manhattan distance traveled along horizontal and vertical grid lines from the origin (0, 0) to the point .
In the code, p.x and p.y are those two projections. You pass a single coordinate value around as a whole and unpack its two components only inside the distance function.3
structure Point where
x : Int
y : Int
deriving Repr
def origin : Point := { x := 0, y := 0 }
def moved : Point := { origin with x := 4, y := -3 }
def manhattan (p : Point) : Nat :=
p.x.natAbs + p.y.natAbs
#eval moved
#eval manhattan movedOutput:
{ x := 4, y := -3 }
7Two lines appear in the output. The first line, { x := 4, y := -3 }, is the new coordinate printed by #eval moved. Because all values in Lean are immutable by default, { origin with x := 4, y := -3 } does not overwrite origin in place; instead, it copies origin and replaces the specified fields to return a fresh Point value.
The second line, 7, is the result of manhattan moved converting each integer’s absolute value to a natural number via .natAbs and computing .
2. Choosing Among Branches with inductive and match
A pending payment has no transaction ID yet, and a failed payment carries a failure reason instead of a transaction ID. By listing three branches with | under inductive PaymentState where and attaching data only to the branches that need it, each payment value belongs to exactly one of the three states.
The expression match s with inspects that state and picks which message to return. For instance, | .paid txId amount => unpacks the ID and amount from a completed payment and formats them on the right-hand side, where s! interpolates expressions inside curly braces into the string.4
A name that builds a value, such as PaymentState.paid, is called a constructor. In #eval describePayment (.paid "tx_901" 15000), Lean already expects a PaymentState, so you can leave off its type name and write .paid. The .paid pattern in match looks for that same constructor and extracts the two values it carries.
A type that chooses exactly one among several branches is written in formulas using the square cup symbol (disjoint union). This symbol means we unite the sets while keeping a tag indicating which branch (constructor) created the value, and the number denotes a single-element set with no extra payload (.pending).
In contrast, the completed branch (.paid) carries both a transaction ID string and a natural-number amount, written as the product , while the failed branch (.failed) carries a single failure-reason string ().
Because the function must return a string regardless of which of the three states arrives, match supplies three answers. When handling a failed payment, the only data you need to reason about is the failure reason actually stored in that branch.5
inductive PaymentState where
| pending
| paid (txId : String) (amount : Nat)
| failed (reason : String)
deriving Repr
def describePayment (s : PaymentState) : String :=
match s with
| .pending => "Payment pending"
| .paid txId amount => s!"Payment complete ({txId}): {amount} KRW"
| .failed reason => s!"Payment failed: {reason}"
#eval describePayment .pending
#eval describePayment (.paid "tx_901" 15000)
#eval describePayment (.failed "limit exceeded")Output:
"Payment pending"
"Payment complete (tx_901): 15000 KRW"
"Payment failed: limit exceeded"Each of the three output lines comes from feeding one of the three payment states into match s with. First, .pending matches the first arm and produces "Payment pending"; on the second line, .paid "tx_901" 15000 matches the second arm, binds txId = "tx_901" and amount = 15000, and plugs them into the curly braces of s!"..." to produce "Payment complete (tx_901): 15000 KRW".
Third, .failed "limit exceeded" extracts reason in the third arm and prints "Payment failed: limit exceeded". If you delete the line | .failed reason => ... from describePayment and run Lean, the compiler immediately catches the omitted PaymentState.failed branch at compile time with a Missing cases error.6
3. Bool and Nat Are Inductive Types Too
Even Bool and Nat from Part 1 are defined as inductive types in the standard library.
Bool: a sum type with two constructors,falseortrueNat: a recursive inductive type defined either aszero(0) or as the successorsucc n(n + 1) of another natural numbern
For example, is the number 2. Knowing which constructors can build a value tells you exactly which cases you need to split on when inspecting it. Mathematical induction on natural numbers splits into 0 and the successor step in the exact same way, and in Part 6 we will apply that same principle to empty lists and non-empty lists.7
In Part 4, we will add type parameters ({α : Type}) to inductive types so we can work with Option α and List α over any element type, and write recursive functions that peel a list one element at a time.
Footnotes
- Lean Language Reference 4.36.0. Inductive Types. Explains constructors and inductive type definitions. ↩
- David Thrane Christiansen. Functional Programming in Lean. Structures. Illustrates declaring and reading fields as well as creating updated copies. ↩
- Lean Language Reference 4.36.0. Inductive Types: Structures · Structures: Projections. Explains single-constructor structures and field projection functions. ↩
- Lean Language Reference 4.36.0. Strings. Explains string interpolation using
s!and curly braces. ↩ - Lean Language Reference 4.36.0. Inductive Types: Declarations · Pattern Matching. Covers how constructors determine the shape of values and how
matchbranches on them. ↩ - Lean Language Reference 4.36.0. Pattern Matching. Explains why pattern matching must cover all possible constructors. ↩
- Lean Language Reference 4.36.0. Natural Numbers: Logical Model · Inductive Types: Recursors. Explains the constructors of natural numbers and the recursion and induction principles derived from them. ↩