2.5. Functional Programming in Lean
Lean is both a proof assistant and a functional programming language. So far we have used Lean mainly to write proofs; in this chapter we turn our attention to the programming side. We will see that the same mechanisms — inductive types, pattern matching and recursion — serve both for writing programs and for reasoning about them, and that this uniformity is precisely what makes Lean well suited for program verification.
The topics of this chapter are: the No Junk and No Confusion principles of
inductive types and their relation to induction and structural recursion; the
match expression; structures and type classes as abstraction mechanisms; the
cases tactic; functions and theorems about lists and binary trees; and,
finally, a first encounter with dependent inductive types, through vectors
whose length is recorded in the type itself.
namespace Ch12
2.5.1. Inductive types revisited
An inductive type is specified by a list of constructors. For example, the
natural numbers are generated by Nat.zero and Nat.succ. Two fundamental
principles govern every inductive type:
-
No Junk: the type contains no values beyond those that can be built by (finitely many) applications of the constructors.
-
No Confusion: values built in different ways are distinct, and every constructor is injective.
For the natural numbers, No Junk means that there is no special value, say
-1 or \varepsilon, that is neither zero nor succ n for some n.
No Confusion means that Nat.zero ≠ Nat.succ n for every n and that
Nat.succ m = Nat.succ n implies m = n. Lean derives these facts
automatically from the type declaration:
example (n : ℕ) : Nat.zero ≠ Nat.succ n := n:ℕ⊢ Nat.zero ≠ n.succ
n:ℕh:Nat.zero = n.succ⊢ False
All goals completed! 🐙
example (m n : ℕ) (h : Nat.succ m = Nat.succ n) :
m = n := m:ℕn:ℕh:m.succ = n.succ⊢ m = n
m:ℕ⊢ m = m
All goals completed! 🐙
There is also a third aspect, often left implicit: values of inductive types
are always finite. The infinite "sequence" succ (succ (succ …)) is not a
natural number. It is precisely finiteness that guarantees that we can reason
by induction and that functions defined by structural recursion terminate.
2.5.2. Structural induction
Structural induction generalizes mathematical induction to any inductive type: to prove that a property holds for all values of the type, it suffices to prove it for each constructor, assuming it holds for that constructor's recursive arguments. There is therefore one subgoal per constructor, and one induction hypothesis for each recursive argument.
For the natural numbers, proving P(n) for all n requires a base case
P(0) and a step \forall k,\ P(k) \to P(k+1). For lists, proving P(xs)
for every list requires the case P([\,]) and the step
\forall y\, ys,\ P(ys) \to P(y :: ys).
As a first example, we prove that no number equals its own successor:
theorem succ_neq_self (n : ℕ) : Nat.succ n ≠ n := n:ℕ⊢ n.succ ≠ n
induction n with
⊢ Nat.succ 0 ≠ 0 All goals completed! 🐙
n':ℕih:n'.succ ≠ n'⊢ (n' + 1).succ ≠ n' + 1 All goals completed! 🐙
In the zero case, the goal Nat.succ 0 ≠ 0 is an instance of No
Confusion. In the succ case, the goal is
Nat.succ (Nat.succ n') ≠ Nat.succ n'; by injectivity of succ it reduces to
the induction hypothesis ih. simp knows these facts and closes both goals.
2.5.3. Structural recursion
The computational counterpart of structural induction is structural recursion: each recursive call is made on an argument obtained by removing exactly one constructor from the original argument. Since values are finite, a function defined this way always terminates, and Lean checks this condition automatically. The classic example is the factorial:
def fact : ℕ → ℕ
| 0 => 1
| n + 1 => (n + 1) * fact n
#eval fact 5
Why does Lean insist so much on termination? Because Lean functions are also
logical objects: every definition f adds to the theory the equations that
define it. If we admitted a "function" satisfying f n = f n + 1, those
equations would be contradictory. We can simulate this situation by declaring
an opaque constant and postulating the equation as an axiom:
opaque immoral : ℕ → ℕ
axiom immoral_eq : ∀ n, immoral n = immoral n + 1
theorem disaster : False := ⊢ False
h:immoral 0 = immoral 0 + 1⊢ False
All goals completed! 🐙
The axiom above makes the logic inconsistent: we have proved False, and from
False any proposition follows.Do not use axioms like this outside
of teaching examples! The #print axioms command shows which axioms a theorem
depends on. Lean rejects the definition def immoral (n : ℕ) := immoral n + 1
precisely to prevent this kind of disaster: termination is essential for
logical consistency.
2.5.4. The match expression
Definitions by equations, such as fact, perform pattern matching at the level
of the definition. Often, however, we want to distinguish cases locally, in
the middle of an expression, without recursion. This is what the match
expression is for. The function below counts the elements of a list that
satisfy a Boolean predicate:
def bcount {α : Type} (p : α → Bool) : List α → ℕ
| [] => 0
| x :: xs =>
match p x with
| true => bcount p xs + 1
| false => bcount p xs
#eval bcount (fun n => n % 2 == 0) [1, 2, 3, 4, 6]
match can also be used in proofs written as terms, as we will see later in
the section on the cases tactic.
2.5.5. Structures
Structures (records) are non-recursive inductive types with a single constructor. Lean offers special syntax for declaring them and automatically generates the constructor and the projection functions:
structure RGB where
red : ℕ
green : ℕ
blue : ℕ
The declaration introduces the constructor RGB.mk and the projections
RGB.red, RGB.green and RGB.blue. There are several ways
to build a value of a structure: applying the constructor positionally, listing
the fields by name, or updating fields of an existing value. A structure can
also extend another one, inheriting its fields:
structure RGBA extends RGB where
alpha : ℕ
def pureRed : RGB := RGB.mk 0xff 0x00 0x00
def pureGreen : RGB :=
{ red := 0x00, green := 0xff, blue := 0x00 }
def semitransparentGreen : RGBA :=
{ pureGreen with alpha := 0x7f }
#eval semitransparentGreen.green
Functions on structures are defined using the projections. The function
shuffle rotates the color channels:
def shuffle (c : RGB) : RGB :=
{ red := c.green, green := c.blue, blue := c.red }
theorem shuffle_shuffle_shuffle (c : RGB) :
shuffle (shuffle (shuffle c)) = c := c:RGB⊢ shuffle (shuffle (shuffle c)) = c
All goals completed! 🐙
The proof that three rotations yield the original color is simply rfl:
unfolding shuffle three times we obtain
{ red := c.red, green := c.green, blue := c.blue }, which is definitionally
equal to c thanks to the eta rule for structures.
2.5.6. Type classes
A type class is a structure that bundles abstract constants (and possibly properties about them). A type becomes an instance of the class when we provide concrete definitions for these constants, and Lean selects the right instance automatically from the type. Type classes will be studied in more detail in the chapter on property-based testing; here we present only the basic idea.
The standard library defines the class Inhabited, which guarantees that a
type has at least one value:
class Inhabited (α : Sort u) where default : α
We can declare instances for concrete types. The library already has instances equivalent to the ones below; we write them explicitly to illustrate the syntax:
instance natInhabited : Inhabited ℕ :=
{ default := 0 }
instance listInhabited {α : Type} : Inhabited (List α) :=
{ default := [] }
An argument in square brackets, such as [Inhabited α], is an instance-implicit
argument: Lean fills it in by searching for a registered instance for the type
in question. This lets us define a total head function that returns the
default value when the list is empty:
def head {α : Type} [Inhabited α] : List α → α
| [] => Inhabited.default
| x :: _ => x
#eval (head [] : ℕ)
Instances can be built compositionally. If β is inhabited, then the
function type α → β is too (via the constant function); if α and β are
inhabited, so is the product α × β:
instance funInhabited {α β : Type} [Inhabited β] :
Inhabited (α → β) :=
{ default := fun _ ↦ Inhabited.default }
instance prodInhabited {α β : Type}
[Inhabited α] [Inhabited β] :
Inhabited (α × β) :=
{ default := (Inhabited.default, Inhabited.default) }
Instance search is, in fact, a small form of logic programming: to solve
Inhabited (ℕ × List ℕ), Lean uses prodInhabited, which produces the
subgoals Inhabited ℕ and Inhabited (List ℕ), solved in turn by the other
instances.
2.5.7. The cases tactic
The induction tactic performs a case distinction on the constructors and
provides induction hypotheses. When the induction hypotheses are not needed, we
can use the cases tactic, which only distinguishes the cases. For example,
head [head xs] = head xs follows by direct computation in each case:
theorem head_head {α : Type} [Inhabited α] (xs : List α) :
head [head xs] = head xs := α:Typeinst✝:Inhabited αxs:List α⊢ head [head xs] = head xs
cases xs with
α:Typeinst✝:Inhabited α⊢ head [head []] = head [] All goals completed! 🐙
α:Typeinst✝:Inhabited αx:αxs':List α⊢ head [head (x :: xs')] = head (x :: xs') All goals completed! 🐙
The same proof can be written as a term, using match:
theorem head_head_match {α : Type} [Inhabited α]
(xs : List α) :
head [head xs] = head xs :=
match xs with
α:Typeinst✝:Inhabited αxs:List α⊢ head [head []] = head [] α:Typeinst✝:Inhabited αxs:List α⊢ head [head []] = head [] All goals completed! 🐙
α:Typeinst✝:Inhabited αxs:List αhead✝:αtail✝:List α⊢ head [head (head✝ :: tail✝)] = head (head✝ :: tail✝) α:Typeinst✝:Inhabited αxs:List αhead✝:αtail✝:List α⊢ head [head (head✝ :: tail✝)] = head (head✝ :: tail✝) All goals completed! 🐙
The cases tactic also applies to hypotheses. Applied to an equality between
two values built from constructors, it implements the No Confusion
principles: if the constructors are the same, cases deduces the equality of
the arguments (injectivity); if they are different, the hypothesis is
contradictory and the goal is closed without generating any subgoal.
theorem injection_example {α : Type} (x y : α)
(xs ys : List α)
(h : x :: xs = y :: ys) : x = y ∧ xs = ys := α:Typex:αy:αxs:List αys:List αh:x :: xs = y :: ys⊢ x = y ∧ xs = ys
α:Typex:αxs:List α⊢ x = x ∧ xs = xs
All goals completed! 🐙
theorem distinctness_example {α : Type} (y : α)
(ys : List α)
(h : [] = y :: ys) : False := α:Typey:αys:List αh:[] = y :: ys⊢ False
All goals completed! 🐙
Finally, cases can be applied to a proof of a disjunction. Combined with the
law of excluded middle, Classical.em, this gives us reasoning by cases on any
proposition:
theorem min_add_add (l m n : ℕ) :
min (m + l) (n + l) = min m n + l := l:ℕm:ℕn:ℕ⊢ min (m + l) (n + l) = min m n + l
cases Classical.em (m ≤ n) with
l:ℕm:ℕn:ℕh:m ≤ n⊢ min (m + l) (n + l) = min m n + l All goals completed! 🐙
l:ℕm:ℕn:ℕh:¬m ≤ n⊢ min (m + l) (n + l) = min m n + l All goals completed! 🐙
In the first case, m ≤ n, both sides reduce to m + l; in the second, both
reduce to n + l.
2.5.8. Lists
Lists are the most widely used data type in functional programming. In this section we redefine some classic functions — so that we can study them closely — and prove properties about them.
def map {α β : Type} (f : α → β) : List α → List β
| [] => []
| x :: xs => f x :: map f xs
def length {α : Type} : List α → ℕ
| [] => 0
| _ :: xs => length xs + 1
2.5.8.1. Partial functions
What should the head of an empty list be? Lean functions must be total, so we
have to make a decision. We have already seen one solution, head, which
returns a default value. Two other common solutions are to return an Option,
signaling the possible absence of a result, or to require as an argument a
proof that the list is not empty:
def headOpt {α : Type} : List α → Option α
| [] => Option.none
| x :: _ => Option.some x
def headPre {α : Type} : (xs : List α) → xs ≠ [] → α
α:Typehxs:[] ≠ []⊢ α α:Typehxs:[] ≠ []⊢ α All goals completed! 🐙
| x :: _, _ => x
In headPre, the type of the second argument depends on the value of the
first: it is a dependent type. In the [] case, the hypothesis
hxs : [] ≠ [] is contradictory, and the simp at * tactic derives False
from it, which allows us to produce a value of any type. We will return to this
idea in the chapter on programming with dependent types.
2.5.8.2. The zip function
The zip function combines two lists element by element, stopping when the
shorter one runs out. Note that we need three equations, not two: since Lean
requires pattern matching to be exhaustive, we must also cover the case in
which the first list is non-empty and the second is empty.
def zip {α β : Type} : List α → List β → List (α × β)
| x :: xs, y :: ys => (x, y) :: zip xs ys
| [], _ => []
| _ :: _, [] => []
#eval zip [1, 2, 3] ['a', 'b']
2.5.8.3. Properties of map
The following properties are the functor laws for lists, together with the
distributivity of map over concatenation. All of them are proved by induction
on the list, and in all of them the inductive step consists of unfolding the
definition of map and using the induction hypothesis.
theorem map_ident {α : Type} (xs : List α) :
map (fun x ↦ x) xs = xs := α:Typexs:List α⊢ map (fun x => x) xs = xs
induction xs with
α:Type⊢ map (fun x => x) [] = [] All goals completed! 🐙
α:Typex:αxs:List αih:map (fun x => x) xs = xs⊢ map (fun x => x) (x :: xs) = x :: xs All goals completed! 🐙
theorem map_comp {α β γ : Type} (f : α → β) (g : β → γ)
(xs : List α) :
map g (map f xs) = map (fun x ↦ g (f x)) xs := α:Typeβ:Typeγ:Typef:α → βg:β → γxs:List α⊢ map g (map f xs) = map (fun x => g (f x)) xs
induction xs with
α:Typeβ:Typeγ:Typef:α → βg:β → γ⊢ map g (map f []) = map (fun x => g (f x)) [] All goals completed! 🐙
α:Typeβ:Typeγ:Typef:α → βg:β → γx:αxs:List αih:map g (map f xs) = map (fun x => g (f x)) xs⊢ map g (map f (x :: xs)) = map (fun x => g (f x)) (x :: xs) All goals completed! 🐙
theorem map_append {α β : Type} (f : α → β)
(xs ys : List α) :
map f (xs ++ ys) = map f xs ++ map f ys := α:Typeβ:Typef:α → βxs:List αys:List α⊢ map f (xs ++ ys) = map f xs ++ map f ys
induction xs with
α:Typeβ:Typef:α → βys:List α⊢ map f ([] ++ ys) = map f [] ++ map f ys All goals completed! 🐙
α:Typeβ:Typef:α → βys:List αx:αxs:List αih:map f (xs ++ ys) = map f xs ++ map f ys⊢ map f (x :: xs ++ ys) = map f (x :: xs) ++ map f ys All goals completed! 🐙
Theorems such as map_comp are examples of theorems for free, in Wadler's
sense: they hold for any polymorphic function with the type of map, by
parametricity arguments.
2.5.8.4. Length of zip
The length of zip xs ys is the minimum of the lengths of xs and ys. The
proof is instructive because it requires generalizing the induction
hypothesis. If we did induction on xs with ys fixed, the induction
hypothesis would talk about zip xs' ys, but in the step we need
zip xs' ys', where ys' is the tail of ys. The generalizing ys clause
makes the induction hypothesis hold for every ys. In the inductive step, we
then do a case analysis on ys.
theorem min_add_add_one (m n : ℕ) :
min (m + 1) (n + 1) = min m n + 1 := m:ℕn:ℕ⊢ min (m + 1) (n + 1) = min m n + 1
All goals completed! 🐙
theorem length_zip {α β : Type} (xs : List α)
(ys : List β) :
length (zip xs ys) = min (length xs) (length ys) := α:Typeβ:Typexs:List αys:List β⊢ length (zip xs ys) = min (length xs) (length ys)
induction xs generalizing ys with
α:Typeβ:Typeys:List β⊢ length (zip [] ys) = min (length []) (length ys) All goals completed! 🐙
α:Typeβ:Typex:αxs:List αih:∀ (ys : List β), length (zip xs ys) = min (length xs) (length ys)ys:List β⊢ length (zip (x :: xs) ys) = min (length (x :: xs)) (length ys)
cases ys with
α:Typeβ:Typex:αxs:List αih:∀ (ys : List β), length (zip xs ys) = min (length xs) (length ys)⊢ length (zip (x :: xs) []) = min (length (x :: xs)) (length []) All goals completed! 🐙
α:Typeβ:Typex:αxs:List αih:∀ (ys : List β), length (zip xs ys) = min (length xs) (length ys)y:βys':List β⊢ length (zip (x :: xs) (y :: ys')) = min (length (x :: xs)) (length (y :: ys'))
All goals completed! 🐙
2.5.9. Binary trees
Inductive types whose constructors have several recursive arguments define
tree-shaped structures. A binary tree with labels of type α is either empty,
or a node with a label and two subtrees:
inductive Tree (α : Type) : Type where
| nil : Tree α
| node : α → Tree α → Tree α → Tree α
Thanks to the principles of inductive types, these trees have no pointers, no
cycles and no infinite branches: every tree is a finite term. The function
mirror produces the mirror image of a tree, recursively swapping the left and
right subtrees:
def mirror {α : Type} : Tree α → Tree α
| Tree.nil => Tree.nil
| Tree.node a l r => Tree.node a (mirror r) (mirror l)
Mirroring twice gives back the original tree. In the proof by induction, the
node case has two induction hypotheses, one for each subtree:
theorem mirror_mirror {α : Type} (t : Tree α) :
mirror (mirror t) = t := α:Typet:Tree α⊢ mirror (mirror t) = t
induction t with
α:Type⊢ mirror (mirror Tree.nil) = Tree.nil All goals completed! 🐙
α:Typea:αl:Tree αr:Tree αil:mirror (mirror l) = lir:mirror (mirror r) = r⊢ mirror (mirror (Tree.node a l r)) = Tree.node a l r All goals completed! 🐙
It is also possible to write the proof as a recursive function, in which the
recursive calls to mirror_mirror_calc play the role of the induction
hypotheses. The calc block makes the chain of equalities explicit:
theorem mirror_mirror_calc {α : Type} :
∀ t : Tree α, mirror (mirror t) = t
α:Type⊢ mirror (mirror Tree.nil) = Tree.nil α:Type⊢ mirror (mirror Tree.nil) = Tree.nil All goals completed! 🐙
| Tree.node a l r =>
calc mirror (mirror (Tree.node a l r))
= Tree.node a (mirror (mirror l))
(mirror (mirror r)) := α:Typea:αl:Tree αr:Tree α⊢ mirror (mirror (Tree.node a l r)) = Tree.node a (mirror (mirror l)) (mirror (mirror r)) All goals completed! 🐙
_ = Tree.node a l r := α:Typea:αl:Tree αr:Tree α⊢ Tree.node a (mirror (mirror l)) (mirror (mirror r)) = Tree.node a l r
All goals completed! 🐙
This style highlights the correspondence between proofs by induction and
functions defined by structural recursion: a proof by induction is a
recursive function that, given t, builds a proof of the property for t.
2.5.10. Dependent inductive types
A dependent inductive type is a family of types indexed by terms, in which
the index may vary from constructor to constructor. The canonical example is
the type Vec α n of lists of elements of α of length exactly n:
inductive Vec (α : Type) : ℕ → Type where
| nil : Vec α 0
| cons : α → {n : ℕ} → Vec α n → Vec α (n + 1)
The constructor nil produces a vector of length 0; cons takes a vector of
length n and produces one of length n + 1. The length is therefore checked
statically by the type checker:
#check Vec.cons 1 (Vec.cons 2 (Vec.cons 3 Vec.nil))
An important consequence is that operations such as "head" can be defined
without Option and without an explicit precondition: it is enough to require
the length to be of the form n + 1. Lean sees that the nil case is
impossible, since 0 does not unify with n + 1:
def Vec.head {α : Type} {n : ℕ} : Vec α (n + 1) → α
| Vec.cons a _ => a
We can convert between vectors and lists. The conversion from Vec to List
simply forgets the index; in the opposite direction, the type of the result
depends on the input list:
def listOfVec {α : Type} : ∀ {n}, Vec α n → List α
| _, Vec.nil => []
| _, Vec.cons a v => a :: listOfVec v
def vecOfList {α : Type} :
∀ xs : List α, Vec α (List.length xs)
| [] => Vec.nil
| x :: xs => Vec.cons x (vecOfList xs)
Finally, we prove that the list obtained from a vector of length n does
indeed have length n. The proof is a recursive function on the vector, and
the recursive call provides the induction hypothesis:
theorem length_listOfVec {α : Type} :
∀ (n : ℕ) (v : Vec α n), List.length (listOfVec v) = n
α:Type⊢ (listOfVec Vec.nil).length = 0 α:Type⊢ (listOfVec Vec.nil).length = 0 All goals completed! 🐙
α:Typea✝:αn✝:ℕv:Vec α n✝⊢ (listOfVec (Vec.cons a✝ v)).length = n✝ + 1 α:Typea✝:αn✝:ℕv:Vec α n✝⊢ (listOfVec (Vec.cons a✝ v)).length = n✝ + 1
All goals completed! 🐙
The chapter on programming with dependent types explores this idea in more detail, with indexed lists, safe indexing and heterogeneous lists.
end Ch12
2.5.11. Exercises
-
Define a function
reverse : List α → List αby structural recursion and prove thatlength (reverse xs) = length xs, using thelengthfunction from this chapter. -
Prove that
map f (reverse xs) = reverse (map f xs). You will need an auxiliary lemma aboutmapand concatenation. -
Define a function
size : Tree α → ℕthat counts the nodes of a tree and prove thatsize (mirror t) = size t. -
Prove the statement below using
caseson an equality:theorem succ_inj (m n : ℕ) (h : m + 1 = n + 1) : m = n
-
Define a structure
Pointwith integer coordinatesxandy, a functionswapthat exchanges the coordinates, and prove thatswap (swap p) = p. -
Define
Vec.map : (α → β) → Vec α n → Vec β nandVec.zip, which combines two vectors of the same length. Note how the type ofVec.zipmakes the third case of thezipfunction on lists unnecessary. -
Prove that
listOfVec (vecOfList xs) = xsfor every listxs.