2.2. Programs and Theorems in Lean

In the previous chapter we studied simple type theory: types, terms, and typing rules. We now see how Lean uses these foundations to define data types and functions and to state theorems about those functions. Lean thus supports two modes of use that coexist in the same file:

  • programming: we define functions, whose types are checked by the compiler and which can be executed;

  • proving: we state properties of these functions and prove them formally.

The focus of this chapter is the first mode, together with the statement of theorems. Proof techniques proper (tactics, structured proofs, induction) will be studied in detail in the next chapters. Even so, so that every theorem in this text is verified, at the end we show a few short proofs by induction, which serve as a preview of what lies ahead.

2.2.1. Inductive types

An inductive type consists of all the values that can be built by a finite number of applications of its constructors, and only those. The declaration of an inductive type lists the constructors and their types.

2.2.1.1. Natural numbers

The simplest and most important example is that of the natural numbers in unary notation. To avoid clashing with the library type Nat, we call our version MyNat:

namespace Ch09 inductive MyNat : Type where | zero : MyNat | succ : MyNat → MyNat

The constructor zero represents the number zero, and succ n represents the successor of n. Every natural number is obtained by finitely many applications of succ to zero:

0,\quad \mathsf{succ}\;0,\quad \mathsf{succ}\;(\mathsf{succ}\;0),\quad \ldots

The words "only those" in the definition of an inductive type matter: there is no MyNat other than these. This is what later justifies defining functions by cases on the constructors and proving properties by induction.

The standard library type Nat (written ℕ with Mathlib) is defined in exactly this way. The #check and #print commands let us inspect it:

Nat.zero : ℕ#check Nat.zero Nat.succ (n : ℕ) : ℕ#check Nat.succ inductive Nat : Type number of parameters: 0 constructors: Nat.zero : ℕ Nat.succ : ℕ → ℕ#print Nat
Nat.zero : ℕ
Nat.succ (n : ℕ) : ℕ
inductive Nat : Type
number of parameters: 0
constructors:
Nat.zero : ℕ
Nat.succ : ℕ → ℕ

Internally, Lean represents Nat efficiently (using arbitrary-precision integers), but from the logical point of view it is the inductive type above. The literals 0, 1, 2, … are notations for Nat.zero, Nat.succ Nat.zero, and so on.

2.2.1.2. Arithmetic expressions

Inductive types are not limited to numbers. The following type represents arithmetic expressions over the integers:

inductive AExp : Type where | num : ℤ → AExp | var : String → AExp | add : AExp → AExp → AExp | mul : AExp → AExp → AExp deriving Repr

A value of AExp is an expression tree: num i is an integer literal i, var x is a variable named x, and add e₁ e₂ and mul e₁ e₂ are binary nodes. For example, the expression 2 \cdot (x + 1) is represented by AExp.mul (AExp.num 2) (AExp.add (AExp.var "x") (AExp.num 1)). The deriving Repr clause asks Lean to automatically generate a function for displaying values of the type, which lets us use them with #eval.

2.2.1.3. Polymorphic lists

Inductive types may have parameters. The type of lists is parameterized by the type α of its elements:

inductive MyList (α : Type) where | nil : MyList α | cons : α → MyList α → MyList α

The constructor nil is the empty list, and cons x xs is the list with head x and tail xs. Note that MyList on its own is not a type: it is a function from types to types, a type constructor.

Ch09.MyList (α : Type) : Type#check MyList MyList.cons 1 (MyList.cons 2 MyList.nil) : MyList ℕ#check MyList.cons 1 (MyList.cons 2 MyList.nil)
Ch09.MyList (α : Type) : Type
MyList.cons 1 (MyList.cons 2 MyList.nil) : MyList ℕ

The standard library defines List in exactly this way and provides convenient notations: [] denotes List.nil, x :: xs denotes List.cons x xs, and [x₁, …, xN] denotes x₁ :: … :: xN :: []. From now on we use the library's List type.

2.2.2. Defining functions

2.2.2.1. Pattern matching

Functions on inductive types are defined by pattern matching: we give one equation for each possible shape of the argument. The classic example is the Fibonacci sequence:

def fib : ℕ → ℕ | 0 => 0 | 1 => 1 | n + 2 => fib (n + 1) + fib n 55#eval fib 10
55

Patterns may be constructors (Nat.zero, Nat.succ n) or the equivalent numeric forms (0, n + 1, n + 2). Lean checks that the patterns are exhaustive, that is, that they cover every case; if an equation were missing, the definition would be rejected.

2.2.2.2. Structural recursion

Addition of natural numbers can be defined by structural recursion on the second argument: adding zero leaves m unchanged, and adding the successor of n means taking the successor of the sum with n.

def add : ℕ → ℕ → ℕ | m, Nat.zero => m | m, Nat.succ n => Nat.succ (add m n)

Each recursive call removes one succ from the second argument, so the recursion always terminates. To run the function, we have two commands:

9#eval add 2 7 9#reduce add 2 7
9
9

The #eval command compiles the term and runs it efficiently. #reduce, in contrast, normalizes the term using the reduction rules of the logical core: it is slower, but it uses only Lean's core logic. This distinction matters: in proofs, what counts is logical reduction, not compiled code.

Multiplication is defined analogously, using addition. When an argument is irrelevant in an equation, we use the wildcard pattern _:

def mul : ℕ → ℕ → ℕ | _, Nat.zero => Nat.zero | m, Nat.succ n => add m (mul m n)

Exponentiation, in turn, uses multiplication:

def power : ℕ → ℕ → ℕ | _, Nat.zero => 1 | m, Nat.succ n => mul m (power m n) 32#eval power 2 5
32

2.2.2.3. Named parameters

In power, the first argument is never taken apart: it is merely passed along. In this case we can declare it as a named parameter, to the left of the :, and pattern-match only on the remaining arguments:

def powerParam (m : ℕ) : ℕ → ℕ | Nat.zero => 1 | Nat.succ n => mul m (powerParam m n)

Notice that in the recursive call the parameter m must still be passed explicitly: powerParam still has type ℕ → ℕ → ℕ.

2.2.3. Higher-order functions

A higher-order function takes another function as an argument (or returns one as its result). An instructive example is iter, which applies a function f exactly n times to an initial value z:

def iter (α : Type) (z : α) (f : α → α) : ℕ → α | Nat.zero => z | Nat.succ n => f (iter α z f n)

That is, \mathsf{iter}\;\alpha\;z\;f\;n = f^n(z). With iter, exponentiation becomes a one-liner: multiply by m, n times, starting from 1. Note the use of the partial application mul m : ℕ → ℕ.

def powerIter (m n : ℕ) : ℕ := iter ℕ 1 (mul m) n 32#eval powerIter 2 5
32

List concatenation, with the element type as an explicit argument, is defined by recursion on the first list:

def append (α : Type) : List α → List α → List α | [], ys => ys | x :: xs, ys => x :: append α xs ys [3, 1, 4, 1, 5]#eval append ℕ [3, 1] [4, 1, 5]
[3, 1, 4, 1, 5]

2.2.4. Implicit arguments

In append ℕ [3, 1] [4, 1, 5], the argument ℕ is redundant: it can be deduced from the type of the lists. Lean distinguishes two kinds of arguments:

  • explicit arguments, declared in parentheses ( ), which we must supply in every call;

  • implicit arguments, declared in braces { }, which Lean infers from the context and which we can (and should) omit.

Rewriting concatenation with an implicit type:

def appendImplicit {α : Type} : List α → List α → List α | [], ys => ys | x :: xs, ys => x :: appendImplicit xs ys [3, 1, 4, 1, 5]#eval appendImplicit [3, 1] [4, 1, 5]
[3, 1, 4, 1, 5]

When we need to supply an implicit argument explicitly, we use the prefix @, which makes all of the function's arguments explicit:

@appendImplicit : {α : Type} → List α → List α → List α#check @appendImplicit [3, 1, 4, 1, 5]#eval @appendImplicit ℕ [3, 1] [4, 1, 5]
@appendImplicit : {α : Type} → List α → List α → List α
[3, 1, 4, 1, 5]

List reversal is another typical example, using the library's concatenation ++:

def reverse {α : Type} : List α → List α | [] => [] | x :: xs => reverse xs ++ [x] [3, 2, 1]#eval reverse [1, 2, 3]
[3, 2, 1]

Two higher-order functions that are ubiquitous in functional programming are map, which applies a function to every element, and foldr, which combines the elements with a binary operator starting from an initial value:

def map {α β : Type} (f : α → β) : List α → List β | [] => [] | x :: xs => f x :: map f xs def foldr {α β : Type} (f : α → β → β) (v : β) : List α → β | [] => v | x :: xs => f x (foldr f v xs) [1, 4, 9, 16]#eval map (fun n ↦ n * n) [1, 2, 3, 4] 10#eval foldr (· + ·) 0 [1, 2, 3, 4]
[1, 4, 9, 16]
10

The notation (· + ·) abbreviates fun x y ↦ x + y.

2.2.5. An expression evaluator

Let us now give meaning to the expressions of AExp. For this we need to know the values of the variables, which is provided by an environment, a function mapping variable names to integer values:

\mathit{env} : \mathsf{String} \to \mathbb{Z}

For example, fun x ↦ if x = "y" then 17 else 0 is the environment in which y has value 17 and every other variable has value 0. The function eval interprets an expression in an environment, by recursion on the structure of the expression:

def eval (env : String → ℤ) : AExp → ℤ | AExp.num i => i | AExp.var x => env x | AExp.add e₁ e₂ => eval env e₁ + eval env e₂ | AExp.mul e₁ e₂ => eval env e₁ * eval env e₂ def env₀ : String → ℤ := fun x ↦ if x = "y" then 17 else 0 -- 2 * (y + 1) def e₀ : AExp := AExp.mul (AExp.num 2) (AExp.add (AExp.var "y") (AExp.num 1)) 36#eval eval env₀ e₀
36

An expression simplifier transforms an expression into a simpler one with the same value. The version below eliminates the neutral element of addition when it appears literally, and recursively simplifies the subexpressions:

def simplify : AExp → AExp | .add (.num 0) e => simplify e | .add e (.num 0) => simplify e | .add e₁ e₂ => .add (simplify e₁) (simplify e₂) | .mul e₁ e₂ => .mul (simplify e₁) (simplify e₂) | e => e -- (0 + x) * 3 Ch09.AExp.mul (Ch09.AExp.var "x") (Ch09.AExp.num 3)#eval simplify (AExp.mul (AExp.add (AExp.num 0) (AExp.var "x")) (AExp.num 3))
Ch09.AExp.mul (Ch09.AExp.var "x") (Ch09.AExp.num 3)

The notation .add, .num, etc. abbreviates AExp.add, AExp.num: since Lean knows that the expected type is AExp, the prefix can be omitted. The patterns are tried in order, from top to bottom: the third equation is used only when neither operand is the literal zero. The natural question is: is the simplifier correct? That is, for every environment env and every expression e, does eval env (simplify e) = eval env e hold? This is a property we can state as a theorem and prove — we will do so at the end of the chapter.

2.2.6. Termination

Lean only accepts function definitions for which it can prove termination. For simple recursive functions, it automatically checks that the recursion is structural: each recursive call receives a strictly smaller argument (an immediate subterm of the original argument). In add,

\mathsf{add}\; m\; (\mathsf{succ}\; n) \;\text{ calls }\; \mathsf{add}\; m\; n

and n is a subterm of \mathsf{succ}\;n, so the argument decreases at every step. A definition that does not decrease its argument is rejected:

def fail to show termination for Ch09.loop with errors failed to infer structural recursion: Not considering parameter n of Ch09.loop: it is unchanged in the recursive calls no parameters suitable for structural recursion well-founded recursion cannot be used, `Ch09.loop` does not take any (non-fixed) argumentsloop (n : ℕ) : ℕ := loop n + 1
fail to show termination for
  Ch09.loop
with errors
failed to infer structural recursion:
Not considering parameter n of Ch09.loop:
  it is unchanged in the recursive calls
no parameters suitable for structural recursion

well-founded recursion cannot be used, `Ch09.loop` does not take any (non-fixed) arguments

Why so much rigor? If loop were accepted, we would have loop n = loop n + 1, from which 0 = 1 follows. The consequence of the termination requirement is that all functions defined in Lean are total: they return a value for every input. This is essential for the logical consistency of the system, since, by the Curry-Howard isomorphism, functions are also proofs.

2.2.7. Stating theorems

The theorem command states a property as a formal proposition. Its form is analogous to that of def: the proposition takes the place of the type, and the proof takes the place of the body.

  • In def name : type := definition, the type is a data type and the body is the definition.

  • In theorem name : proposition := proof, the type is a proposition and the body is a proof.

While we do not yet have the proof, we can write sorry in its place. Lean accepts the statement, issuing a warning, and the theorem can be used in other parts of the development. This is a practical way to plan a theory before proving it:

theorem add_comm (m n : ℕ) : add m n = add n m := sorry

Here are some natural statements about the functions we have defined:

theorem add_comm (m n : ℕ) :
    add m n = add n m := sorry

theorem add_assoc (l m n : ℕ) :
    add (add l m) n = add l (add m n) := sorry

theorem mul_comm (m n : ℕ) :
    mul m n = mul n m := sorry

theorem mul_assoc (l m n : ℕ) :
    mul (mul l m) n = mul l (mul m n) := sorry

theorem mul_add (l m n : ℕ) :
    mul l (add m n) = add (mul l m) (mul l n) := sorry

theorem reverse_reverse {α : Type} (xs : List α) :
    reverse (reverse xs) = xs := sorry

The last one states that reversal is an involution: reversing twice gives back the original list. Notice that the statements are universally quantified over their parameters: add_comm holds for all natural numbers m and n.

Besides theorem, there are two related commands:

  • axiom works like theorem, but the proposition is assumed without proof;

  • opaque works like def, but without a body: the value exists, but it is not specified.

opaque a : ℤ opaque b : ℤ axiom a_less_b : a < b

Axioms must be used with great care: a contradictory axiom (for example, axiom bad : False) makes every statement provable. The command #print axioms shows which axioms a proof depends on.

2.2.8. A preview: first proofs

Although tactics will only be studied in the next chapter, it is worth seeing right away how some of the statements above are proved. The tactic induction n with splits the proof into one case per constructor; in the succ case we gain the induction hypothesis ih. The tactic simp [add, …] unfolds the definitions and rewrites with the facts provided.

theorem add_zero_left (n : ℕ) : add 0 n = n := n:ℕ⊢ add 0 n = n induction n with ⊢ add 0 0 = 0 All goals completed! 🐙 n:ℕih:add 0 n = n⊢ add 0 (n + 1) = n + 1 All goals completed! 🐙 theorem add_succ_left (m n : ℕ) : add (Nat.succ m) n = Nat.succ (add m n) := m:ℕn:ℕ⊢ add m.succ n = (add m n).succ induction n with m:ℕ⊢ add m.succ 0 = (add m 0).succ All goals completed! 🐙 m:ℕn:ℕih:add m.succ n = (add m n).succ⊢ add m.succ (n + 1) = (add m (n + 1)).succ All goals completed! 🐙 theorem add_comm (m n : ℕ) : add m n = add n m := m:ℕn:ℕ⊢ add m n = add n m induction n with m:ℕ⊢ add m 0 = add 0 m All goals completed! 🐙 m:ℕn:ℕih:add m n = add n m⊢ add m (n + 1) = add (n + 1) m All goals completed! 🐙 theorem add_assoc (l m n : ℕ) : add (add l m) n = add l (add m n) := l:ℕm:ℕn:ℕ⊢ add (add l m) n = add l (add m n) induction n with l:ℕm:ℕ⊢ add (add l m) 0 = add l (add m 0) All goals completed! 🐙 l:ℕm:ℕn:ℕih:add (add l m) n = add l (add m n)⊢ add (add l m) (n + 1) = add l (add m (n + 1)) All goals completed! 🐙

For lists, induction is on the list, with the cases nil and cons. The proof that reverse is an involution needs an auxiliary lemma about reversing a concatenation:

theorem reverse_append {α : Type} (xs ys : List α) : reverse (xs ++ ys) = reverse ys ++ reverse xs := α:Typexs:List αys:List α⊢ reverse (xs ++ ys) = reverse ys ++ reverse xs induction xs with α:Typeys:List α⊢ reverse ([] ++ ys) = reverse ys ++ reverse [] All goals completed! 🐙 α:Typeys:List αx:αxs:List αih:reverse (xs ++ ys) = reverse ys ++ reverse xs⊢ reverse (x :: xs ++ ys) = reverse ys ++ reverse (x :: xs) All goals completed! 🐙 theorem reverse_reverse {α : Type} (xs : List α) : reverse (reverse xs) = xs := α:Typexs:List α⊢ reverse (reverse xs) = xs induction xs with α:Type⊢ reverse (reverse []) = [] All goals completed! 🐙 α:Typex:αxs:List αih:reverse (reverse xs) = xs⊢ reverse (reverse (x :: xs)) = 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! 🐙

Finally, the correctness of the simplifier. Here we use fun_induction, which performs induction following exactly the cases of the definition of simplify, and in each case simp unfolds eval and simplify and uses the induction hypotheses:

theorem simplify_correct (env : String → ℤ) (e : AExp) : eval env (simplify e) = eval env e := env:String → ℤe:AExp⊢ eval env (simplify e) = eval env e env:String → ℤe✝:AExpih1✝:eval env (simplify e✝) = eval env e✝⊢ eval env (simplify e✝) = eval env ((AExp.num 0).add e✝)env:String → ℤe✝:AExpx✝:e✝ = AExp.num 0 → Falseih1✝:eval env (simplify e✝) = eval env e✝⊢ eval env (simplify e✝) = eval env (e✝.add (AExp.num 0))env:String → ℤe₁✝:AExpe₂✝:AExpx✝¹:e₁✝ = AExp.num 0 → Falsex✝:e₂✝ = AExp.num 0 → Falseih2✝:eval env (simplify e₁✝) = eval env e₁✝ih1✝:eval env (simplify e₂✝) = eval env e₂✝⊢ eval env ((simplify e₁✝).add (simplify e₂✝)) = eval env (e₁✝.add e₂✝)env:String → ℤe₁✝:AExpe₂✝:AExpih2✝:eval env (simplify e₁✝) = eval env e₁✝ih1✝:eval env (simplify e₂✝) = eval env e₂✝⊢ eval env ((simplify e₁✝).mul (simplify e₂✝)) = eval env (e₁✝.mul e₂✝)env:String → ℤe✝:AExpx✝³:∀ (e : AExp), e✝ = (AExp.num 0).add e → Falsex✝²:∀ (e : AExp), e✝ = e.add (AExp.num 0) → Falsex✝¹:∀ (e₁ e₂ : AExp), e✝ = e₁.add e₂ → Falsex✝:∀ (e₁ e₂ : AExp), e✝ = e₁.mul e₂ → False⊢ eval env e✝ = eval env e✝ env:String → ℤe✝:AExpih1✝:eval env (simplify e✝) = eval env e✝⊢ eval env (simplify e✝) = eval env ((AExp.num 0).add e✝)env:String → ℤe✝:AExpx✝:e✝ = AExp.num 0 → Falseih1✝:eval env (simplify e✝) = eval env e✝⊢ eval env (simplify e✝) = eval env (e✝.add (AExp.num 0))env:String → ℤe₁✝:AExpe₂✝:AExpx✝¹:e₁✝ = AExp.num 0 → Falsex✝:e₂✝ = AExp.num 0 → Falseih2✝:eval env (simplify e₁✝) = eval env e₁✝ih1✝:eval env (simplify e₂✝) = eval env e₂✝⊢ eval env ((simplify e₁✝).add (simplify e₂✝)) = eval env (e₁✝.add e₂✝)env:String → ℤe₁✝:AExpe₂✝:AExpih2✝:eval env (simplify e₁✝) = eval env e₁✝ih1✝:eval env (simplify e₂✝) = eval env e₂✝⊢ eval env ((simplify e₁✝).mul (simplify e₂✝)) = eval env (e₁✝.mul e₂✝)env:String → ℤe✝:AExpx✝³:∀ (e : AExp), e✝ = (AExp.num 0).add e → Falsex✝²:∀ (e : AExp), e✝ = e.add (AExp.num 0) → Falsex✝¹:∀ (e₁ e₂ : AExp), e✝ = e₁.add e₂ → Falsex✝:∀ (e₁ e₂ : AExp), e✝ = e₁.mul e₂ → False⊢ eval env e✝ = eval env e✝ All goals completed! 🐙 end Ch09

These proofs show the general pattern we will explore: we define programs by recursion and prove their properties by induction, following the same structure.

2.2.9. Exercises

  1. Define MyNat.add : MyNat → MyNat → MyNat by recursion on the first argument, and a function toNat : MyNat → ℕ. Check with #eval that toNat (MyNat.add two three) = 5.

  2. Define a function length {α : Type} : List α → ℕ and state (with sorry) the properties:

    theorem length_append {α : Type} (xs ys : List α) :
        length (xs ++ ys) = length xs + length ys := sorry
    theorem length_reverse {α : Type} (xs : List α) :
        length (reverse xs) = length xs := sorry
    
  3. Using iter, define multiplication mulIter m n as n successive additions of m starting from 0. Test it with #eval.

  4. Extend AExp with a constructor sub for subtraction and update eval and simplify. Add to the simplifier the elimination of the neutral element of multiplication (mul (num 1) e and mul e (num 1)). Does the correctness theorem still hold?

  5. Consider the type of binary trees below. Define size, height, and mirror (which swaps the left and right subtrees at every node), and state the theorems.

    inductive BTree (α : Type) : Type where
      | leaf : BTree α
      | node : α → BTree α → BTree α → BTree α
    
    theorem BTree.mirror_mirror {α : Type} (t : BTree α) :
        t.mirror.mirror = t := sorry
    theorem BTree.height_le_size {α : Type} (t : BTree α) :
        t.height ≤ t.size := sorry
    
  6. A more efficient version of reversal uses an accumulator. Define it and state its equivalence with reverse:

    def revAcc {α : Type} : List α → List α → List α
      | [],      acc => acc
      | x :: xs, acc => revAcc xs (x :: acc)
    
    theorem revAcc_eq {α : Type} (xs : List α) :
        revAcc xs [] = reverse xs := sorry
    
  7. Explain why the definition def f (n : ℕ) : ℕ := f (n + 1) is rejected by Lean, and why accepting it would make the logic inconsistent.