Build Your Own Nat: How Inductive Types Define Data in Lean
The problem: how do you describe data from scratch?
Most languages hand you numbers and lists as built in magic. You use them, but you never see how they are made. That is fine for programming, but it is a problem for proving. To prove something about every natural number, you need to know exactly what a natural number is.
Lean answers this with inductive types. You list the ways a value can be built, and that list is the complete definition. Surprisingly, Nat and List in Lean are defined this way too.
The simplest case: a list of options
An inductive type starts with inductive, a name, and then its constructors, the only ways to make a value of that type:
leaninductive Weekday where | monday | tuesday | wednesday | thursday | friday | saturday | sunday deriving Repr def isWeekend : Weekday -> Bool | .saturday => true | .sunday => true | _ => false #eval isWeekend Weekday.sunday #eval isWeekend Weekday.monday #eval Weekday.friday
Lean prints:
lean-- true -- false -- Weekday.friday
There are exactly seven ways to make a Weekday, and no others. That is why the pattern match in isWeekend is accepted: Lean knows the full list. The dot in .saturday is shorthand for Weekday.saturday, letting Lean work out the type. The line deriving Repr asks Lean to generate code for printing values, which #eval needs.
Constructors with arguments: build your own Nat
Constructors can take arguments, including values of the type being defined. Here is a natural number type built from nothing:
leaninductive MyNat where | zero : MyNat | succ (n : MyNat) : MyNat deriving Repr def three : MyNat := MyNat.succ (MyNat.succ (MyNat.succ MyNat.zero)) #check three #eval three #print Nat
Lean prints:
lean-- three : MyNat -- MyNat.succ (MyNat.succ (MyNat.succ (MyNat.zero))) -- inductive Nat : Type -- number of parameters: 0 -- constructors: -- Nat.zero : Nat -- Nat.succ : Nat → Nat
Read MyNat as: a natural number is either zero, or succ n where n is already a natural number. succ is short for successor, meaning "one more than". So three is succ (succ (succ zero)).
The #print Nat output shows that Lean's real Nat has exactly the same shape: two constructors, Nat.zero and Nat.succ. When you write 3, Lean uses an efficient representation under the hood, but logically it is still zero with three successors. This is why the missing case error in the previous lesson mentioned Nat.succ (Nat.succ _): that pattern means "at least two".
Lists are inductive too
A list is either empty, or an element stuck on the front of another list:
leaninductive MyList (α : Type) where | nil : MyList α | cons (head : α) (tail : MyList α) : MyList α deriving Repr #check MyList.cons 1 (MyList.cons 2 MyList.nil) #eval [1, 2, 3] == 1 :: 2 :: 3 :: [] #check List.cons
Lean prints:
lean-- MyList.cons 1 (MyList.cons 2 MyList.nil) : MyList Nat -- true -- List.cons.{u} {α : Type u} (head : α) (tail : List α) : List α
MyList takes a type parameter α, so you can have a list of numbers, a list of strings, and so on. Lean's own List has the same two constructors, List.nil and List.cons. The friendly notation [1, 2, 3] is just sugar for 1 :: 2 :: 3 :: [], where :: is cons and [] is nil, and the true above confirms they are the same value. Ignore the .{u} for now; it is about universe levels and does not matter at this stage.
Animation: three is succ applied three times to zero, and [1, 2, 3] is cons cells ending in the empty list.
Constructors that carry data
Constructors can hold several fields, which lets one type represent several shapes:
leaninductive Shape where | circle (radius : Nat) | rect (width height : Nat) def roughArea : Shape -> Nat | .circle r => 3 * r * r | .rect w h => w * h #eval roughArea (Shape.circle 2) #eval roughArea (Shape.rect 3 4)
Lean prints:
lean-- 12 -- 12
A Shape is either a circle with a radius or a rectangle with a width and height. Pattern matching pulls the fields back out. The "area" uses 3 for pi because these are natural numbers, which is why the function is called roughArea.
Structures: one constructor with named fields
Very often a type has exactly one constructor with several fields, like a point with an x and y. Lean has a special syntax for that, structure:
leanstructure Point where x : Nat y : Nat deriving Repr def origin : Point := { x := 0, y := 0 } def p : Point := Point.mk 3 4 #eval p #eval p.x + p.y #eval { p with x := 10 } #check Point.mk
Lean prints:
lean-- { x := 3, y := 4 } -- 7 -- { x := 10, y := 4 } -- Point.mk (x y : Nat) : Point
A structure is an inductive type with a single constructor, here named Point.mk automatically. You get field access like p.x for free, and { p with x := 10 } makes a copy with one field changed. You can build values either with Point.mk 3 4 or with the { x := ..., y := ... } syntax.
Why this matters for proofs
An inductive definition says two things at once: here are the ways to build a value, and there are no other ways. The second part is the powerful one. If every Nat is either zero or succ n, then to prove something for all natural numbers, it is enough to handle those two cases. That idea is proof by induction, and it comes later in this course.
The same holds for lists: handle the empty list, handle x :: xs assuming you already handled xs, and you have covered every list there is.
Try this
Paste into https://live.lean-lang.org:
leaninductive Tile where | circle (radius : Nat) | square (side : Nat) def perimeterish : Tile -> Nat | .circle r => 6 * r | .square s => 4 * s #eval perimeterish (Tile.square 5)
Add a third constructor triangle (base height : Nat) and watch Lean complain that perimeterish is missing a case. Then add the missing case.
Sources
Define your own data type and a function on it
Define an inductive type `Coin` with three constructors: `penny`, `nickel` and `dime`. Write `value` giving 1, 5 and 10. Then define `total` that adds up the values in a list of coins, and check it on an example.
inductive Coin where | penny | nickel | dime def value : Coin → Nat | .penny => sorry | .nickel => sorry | .dime => sorry def total : List Coin → Nat | [] => sorry | c :: cs => sorry example : total [.dime, .nickel, .penny, .penny] = 17 := by sorry
The official Lean editor runs in your browser and checks the file on Lean's server. Replace every sorry until no errors or warnings are left, then mark it solved.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. What are the two constructors of Lean's Nat?
2. What is [1, 2, 3] shorthand for?
3. What is a structure in Lean?