2.1. Introduction to Lean: Terms and Types
In the previous chapters we studied the Calculus of Constructions (CoC) as the theoretical foundation of modern proof assistants. From this chapter on we work with a concrete tool that implements this foundation: Lean, a proof assistant and functional programming language based on the Calculus of Inductive Constructions (CIC), an extension of CoC with inductive types.
A useful way to think of Lean is as the fusion of two worlds:
\text{Lean} = \text{functional programming} + \text{logic}
As a functional language, Lean lets us define functions, data types, and programs whose well-formedness is checked by the compiler. As a logical system, it lets us state theorems and prove them with a formal guarantee of correctness: a proof accepted by Lean has been checked, step by step, by a small and trustworthy core (the kernel).
In this chapter we start with the simplest part: simple type theory, the fragment of Lean without dependent types, which corresponds essentially to the simply typed lambda calculus. We will see what the types are, what the terms are, how one decides whether a term has a given type (typing rules and derivation trees), and, finally, the problem of type inhabitation, which is the gateway to the Curry-Howard isomorphism and to the use of Lean as a theorem prover.
2.1.1. Types
2.1.1.1. Primitive types and function types
Primitive types represent basic sets of values. In mathematics we usually
write \mathbb{Z}, \mathbb{Q}, \mathbb{B} (Booleans), and
\mathbb{N}; in Lean, the corresponding types are Int, Rat, Bool, and
Nat. The Mathlib library also provides the notations ℤ, ℚ, and ℕ.
The #check command displays the type of a term. It is a diagnostic
command: its result is shown while the file is being elaborated, but it is not
part of any program or proof.
namespace Ch08
#check (3 : ℕ)
#check (-3 : ℤ)
#check true
#check ℕ
Notice the last line: ℕ itself is a term, whose type is Type. In Lean,
types are also terms, and this will be fundamental when we study dependent
types.
From existing types we build function types with the operator \to. A
value of type \sigma \to \tau is a total function that assigns to each
element of \sigma an element of \tau. Some examples:
-
\mathbb{Z} \to \mathbb{Z}is the type of functions from integers to integers; -
\mathbb{Z} \to \mathbb{B}is the type of (computable) predicates on integers; -
(\mathbb{Z} \to \mathbb{Z}) \to \mathbb{Q}is the type of a higher-order function, which takes a function as its argument.
The operator \to is right-associative:
\sigma \to \tau \to \upsilon \;\stackrel{\text{def}}{=}\; \sigma \to (\tau \to \upsilon)
Thus \mathbb{N} \to \mathbb{N} \to \mathbb{N} is the type of a function
that takes a natural number and returns another function from naturals to
naturals. We will see shortly that this is the usual way of representing
functions of several arguments.
2.1.1.2. Type discipline
The type system imposes a discipline: meaningless expressions are rejected
before any computation takes place. In Zermelo-Fraenkel set theory everything
is a set, and an expression such as 1 \in 2 is perfectly well formed (and,
with the usual encoding of the natural numbers, even true!). In Lean, the
corresponding expression is simply a type error: a number is not a collection
whose membership one can ask about. Likewise, adding a number to a Boolean is
rejected:
#check (1 : ℕ) + true
2.1.2. Terms
The terms of simple type theory come in exactly four forms:
-
constants
c, globally declared symbols with a fixed type; -
variables
x, which may be bound or free; -
applications
t\; u, in which the functiontis applied to the argumentu; -
abstractions
\mathbf{fun}\; x{:}\sigma \mapsto t, that is, anonymous functions.
2.1.2.1. Constants
Constants are globally declared symbols with a fixed type, for example
0 : \mathbb{Z},\quad \mathsf{abs} : \mathbb{Z} \to \mathbb{N},\quad \mathsf{prime} : \mathbb{N} \to \mathbb{B}
In Lean, we can declare a constant without giving it a definition by means of
the opaque command. This is useful for reasoning abstractly: we know the
type of the symbol, but nothing about its behavior.We use the names
absZ and prime inside the namespace Ch08 so as not to clash with
Mathlib's abs function.
opaque absZ : ℤ → ℕ
opaque prime : ℕ → Bool
2.1.2.2. Variables
Variables may be bound, when introduced by a fun inside an abstraction, or
free, when declared in the local context. In Lean, the variable command
declares free variables that remain available in subsequent commands; in the
term fun x : ℤ ↦ absZ x, by contrast, the variable x is bound by the
fun.
2.1.2.3. Application
The application t\; u applies a function t : \sigma \to \tau to an
argument u : \sigma, producing a result of type \tau. Application is
left-associative:
t\; u\; v \;\stackrel{\text{def}}{=}\; (t\; u)\; v
This fits perfectly with the right associativity of \to: if
t : \sigma \to \tau \to \upsilon, then t\;u : \tau \to \upsilon and
t\;u\;v : \upsilon. Let us look at some examples using the constants above:
#check absZ 0
#check prime (absZ 0)
#check prime (absZ (-3))
2.1.2.4. Abstraction
The abstraction, or anonymous function,
\mathbf{fun}\; x : \sigma \mapsto t
introduces the total function that maps each x : \sigma to the body t.
In Lean we write fun x : σ ↦ t (or, equivalently, fun x : σ => t).
#check fun x : ℤ ↦ absZ x
#check fun n : ℕ ↦ prime n
2.1.3. Beta reduction
Abstractions have a simple computational semantics, given by beta reduction: applying an anonymous function to an argument amounts to substituting the argument for the parameter in the body.
(\mathbf{fun}\; x{:}\sigma \mapsto t)\; u \;\longrightarrow_\beta\; t[x := u]
Here t[x := u] denotes the term t with all free occurrences of x
replaced by u. For example,
(\mathbf{fun}\; n{:}\mathbb{N} \mapsto n)\; 4 \;\longrightarrow_\beta\; 4 \qquad (\mathbf{fun}\; y{:}\mathbb{Z} \mapsto 1)\; 0 \;\longrightarrow_\beta\; 1
In the second example the parameter does not occur in the body, and the function is constant. Beta reduction also applies when the body uses other functions,
(\mathbf{fun}\; n{:}\mathbb{N} \mapsto \mathsf{square}\;(\mathsf{square}\; n))\; 5 \;\longrightarrow_\beta\; \mathsf{square}\;(\mathsf{square}\; 5)
and the result of a reduction may itself be an abstraction:
(\mathbf{fun}\; x{:}\mathbb{Z} \mapsto (\mathbf{fun}\; y{:}\mathbb{Z} \mapsto x))\; 1 \;\longrightarrow_\beta\; \mathbf{fun}\; y{:}\mathbb{Z} \mapsto 1
Lean carries out these reductions: the #reduce command normalizes a term,
and #eval executes it.
def square (n : ℕ) : ℕ := n * n
#reduce (fun n : ℕ ↦ n) 4
#eval (fun n : ℕ ↦ square (square n)) 5
#reduce (fun x : ℤ ↦ fun y : ℤ ↦ x) 1
2.1.4. Currying and notation
Functions of several arguments are represented by nested abstractions, a technique known as currying (in honor of Haskell Curry):
\mathbf{fun}\; x{:}\sigma \mapsto (\mathbf{fun}\; y{:}\tau \mapsto t) \;:\; \sigma \to \tau \to \upsilon
when t : \upsilon. One advantage of this representation is partial
application: by supplying only the first argument we obtain a function that
waits for the second. To lighten the notation, we use three abbreviations:
-
\sigma \to \tau \to \upsilonabbreviates\sigma \to (\tau \to \upsilon); -
t\; u\; vabbreviates(t\; u)\; v; -
fun (x : σ) (y : τ) ↦ tabbreviatesfun x : σ ↦ (fun y : τ ↦ t).
Moreover, Lean performs type inference: omitted type annotations are
deduced from the context. Of the two terms below, the annotation on x is
unnecessary in the second, since Lean knows that absZ expects an integer.
#check fun (x : ℤ) ↦ absZ x
#check fun x ↦ absZ x
2.1.5. Typing rules
So far we have used #check as a black box. We now formalize when a term
has a type. A typing judgment has the form
C \vdash t : \sigma
and is read "t has type \sigma in the local context C". The context
C is a list of declarations x_1 : \sigma_1, \ldots, x_n : \sigma_n,
which records the types of the free variables. There is one rule for each form
of term.
Constant. A globally declared constant can be used in any context:
\dfrac{c : \sigma \;\text{declared globally}}{C \vdash c : \sigma}\;\text{(Cst)}
Variable. A variable can be used if it is declared in the local context:
\dfrac{(x : \sigma) \in C}{C \vdash x : \sigma}\;\text{(Var)}
If x appears more than once in C, the rightmost occurrence wins: this is
the phenomenon of shadowing. For example, in fun x : ℕ ↦ fun x : Bool ↦ x,
the final occurrence of x refers to the Boolean x.
Application. A function of type \sigma \to \tau applied to an argument
of type \sigma produces a result of type \tau:
\dfrac{C \vdash t : \sigma \to \tau \qquad C \vdash u : \sigma}{C \vdash t\; u : \tau}\;\text{(App)}
Abstraction. To type an anonymous function, we extend the context with the parameter and type the body:
\dfrac{C,\, x : \sigma \vdash t : \tau}{C \vdash \mathbf{fun}\; x{:}\sigma \mapsto t \;:\; \sigma \to \tau}\;\text{(Fun)}
In summary: Cst handles global constants, Var handles variables from the context, App handles applications, and Fun handles the introduction of anonymous functions. Note that the rules are syntax-directed: by looking at the shape of the term we know which rule to apply, which makes type checking an algorithmic procedure.
2.1.6. Derivation trees
A derivation tree formally demonstrates that a term is well typed. Each node is a judgment obtained from its children by one of the rules. As an example, let us show that
\emptyset \vdash \mathbf{fun}\; x{:}\mathbb{Z} \mapsto \mathsf{abs}\; x \;:\; \mathbb{Z} \to \mathbb{N}
The term is an abstraction, so the last rule is Fun, which requires
x{:}\mathbb{Z} \vdash \mathsf{abs}\;x : \mathbb{N}. This is an application,
so we use App, whose premises are discharged by Cst (for \mathsf{abs}) and
Var (for x):
\dfrac{\dfrac{\dfrac{\mathsf{abs} : \mathbb{Z} \to \mathbb{N}\ \text{global}}{x{:}\mathbb{Z} \vdash \mathsf{abs} : \mathbb{Z} \to \mathbb{N}}\,\text{(Cst)} \qquad \dfrac{(x : \mathbb{Z}) \in \{x : \mathbb{Z}\}}{x{:}\mathbb{Z} \vdash x : \mathbb{Z}}\,\text{(Var)}}{x{:}\mathbb{Z} \vdash \mathsf{abs}\; x : \mathbb{N}}\,\text{(App)}}{\emptyset \vdash \mathbf{fun}\; x{:}\mathbb{Z} \mapsto \mathsf{abs}\; x \;:\; \mathbb{Z} \to \mathbb{N}}\,\text{(Fun)}
The construction process is goal-directed (from the bottom of the tree
upward): we start from the target judgment and decompose it into the premises
of the appropriate rule, recursively. At the leaves we always find the rules
Cst or Var, which have no typing premises. This is exactly what Lean's
elaborator does when it answers a #check.
A second example, with currying: let g : \alpha \to \alpha \to \beta be a
constant and a : \alpha another one. Then
\dfrac{\dfrac{\dfrac{}{\vdash g : \alpha \to \alpha \to \beta}\,\text{(Cst)} \qquad \dfrac{}{\vdash a : \alpha}\,\text{(Cst)}}{\vdash g\;a : \alpha \to \beta}\,\text{(App)} \qquad \dfrac{}{\vdash a : \alpha}\,\text{(Cst)}}{\vdash g\;a\;a : \beta}\,\text{(App)}
2.1.7. Type inhabitation
Given a type \sigma, the inhabitation problem asks:
Is there a term
tsuch that\emptyset \vdash t : \sigma?
For function types built only from type variables \alpha, \beta, \gamma,
the question is an interesting one: the type \alpha \to \alpha is inhabited
(by the identity), but \alpha \to \beta is not, since there is no way to
produce an arbitrary \beta from an \alpha. By the Curry-Howard
isomorphism, reading \to as implication, finding an inhabitant is the same
as proving the corresponding formula of intuitionistic propositional logic.
This is why the problem is central to the use of Lean as a prover.
One strategy for finding an inhabitant of \sigma, applied recursively, is:
-
If
\sigma = \tau \to \upsilon, introduce\mathbf{fun}\; x{:}\tau \mapsto \underline{\quad}and try to inhabit\upsilonwithxavailable in the context. -
Otherwise, look for a constant or variable of type
\tau_1 \to \cdots \to \tau_n \to \sigmaand apply it, inhabiting each argument\tau_irecursively.
As an example, let us inhabit
(\alpha \to \beta \to \gamma) \to ((\beta \to \alpha) \to \beta) \to \alpha \to \gamma
Step 1. The type is a function type with three arguments; we introduce three variables:
\mathbf{fun}\; (f{:}\alpha\to\beta\to\gamma)\; (g{:}(\beta\to\alpha)\to\beta)\; (a{:}\alpha) \mapsto \underline{\quad}
It remains to inhabit \gamma with f, g, and a available.
Step 2. The only way to obtain a \gamma is to apply f, which creates
two new holes: f\; \underline{\quad}_\alpha\; \underline{\quad}_\beta. The
hole of type \alpha is filled directly with a. For the one of type
\beta, we apply g, which requires an argument of type
\beta \to \alpha; by rule 1 we introduce
\mathbf{fun}\; b{:}\beta \mapsto \underline{\quad} and fill the hole with
a. The inhabitant we found is
\mathbf{fun}\; f\; g\; a \mapsto f\; a\; (g\;(\mathbf{fun}\; b \mapsto a))
This way of working illustrates the principle of incremental development:
write a syntactically correct program from the very beginning, using
\underline{\quad} for the parts that are still unknown, and fill in the
holes progressively. In Lean, _ represents a hole that the elaborator tries
to infer; if it cannot, it reports the expected type for that hole, which
guides us in the next step.
We can check the inhabitant in Lean, using type variables declared with
variable:
variable (α β γ : Type)
#check (fun (f : α → β → γ) (g : (β → α) → β) (a : α) ↦
f a (g (fun _ ↦ a)))
The same can be done with example, which checks a term against a given type
without introducing any name:
example : (α → β → γ) → ((β → α) → β) → α → γ :=
fun f g a ↦ f a (g (fun _ ↦ a))
example : α → α := fun x ↦ x
example : (α → β) → (β → γ) → α → γ := fun f g x ↦ g (f x)
Note that the last example is function composition; read as a proposition, it is the transitivity of implication.
2.1.8. Lean in practice
We now bring together the commands seen so far in a small session. We would
like to declare types and opaque constants, such as opaque f : A → B.
However, Lean only accepts an opaque declaration when it can show that the
type is inhabited (otherwise we could "declare" an inhabitant of an empty type
and, by the Curry-Howard isomorphism, prove falsehoods!). Since A → B is not
necessarily inhabited, we use the variable command instead, which declares
free variables in the local context, exactly the C of the judgments
C \vdash t : \sigma. A section delimits the scope of these
variables.For opaque absZ : ℤ → ℕ there was no problem: Lean knows
that ℕ is inhabited (by 0), and therefore so is ℤ → ℕ.
section Practice
variable (A B : Type) (f : A → B) (a : A)
#check f a
#check fun x : A ↦ f x
With a function of two arguments, partial application becomes evident: each argument supplied "consumes" one arrow of the type.
variable (g : A → A → B)
#check g
#check g a
#check g a a
#check fun x y : A ↦ g x y
An ill-typed term is rejected with a message that shows exactly which premise of the App rule failed:
#check f (f a)
end Practice
end Ch08
2.1.9. Summary
-
Primitive types:
Int,Nat,Bool, …; function types\sigma \to \tau, with\toright-associative. -
Terms: constants (global symbols with a fixed type), variables (bound by
funor free in the context), applicationst\;u(left-associative), and abstractionsfun x : σ ↦ t. -
Beta reduction:
(\mathbf{fun}\; x \mapsto t)\; u \longrightarrow_\beta t[x := u]. -
Typing rules Cst, Var, App, and Fun, combined into derivation trees.
-
Type inhabitation: finding
tsuch that\emptyset \vdash t : \sigma.
References for further reading: Pierce, Types and Programming Languages (chs. 9–11); de Moura and Ullrich, The Lean 4 Theorem Prover and Programming Language (CADE-28, 2021); Sørensen and Urzyczyn, Lectures on the Curry-Howard Isomorphism (2006).
2.1.10. Exercises
-
Write the types below with all parentheses made explicit:
\alpha \to \beta \to \alpha \to \gammaand(\alpha \to \beta) \to \alpha \to \beta. -
Write the terms below with all parentheses made explicit:
f\;a\;(g\;b)\;cand\mathbf{fun}\; x\; y \mapsto h\; y\; x. -
Reduce to normal form by beta reduction:
(\mathbf{fun}\; f \mapsto \mathbf{fun}\; x \mapsto f\;(f\;x))\;(\mathbf{fun}\; y \mapsto y + 1)\;0. -
Build the derivation tree for
\emptyset \vdash \mathbf{fun}\; (f{:}\alpha \to \beta)\; (x{:}\alpha) \mapsto f\;x : (\alpha \to \beta) \to \alpha \to \beta. -
Find inhabitants for the following types and check them in Lean by replacing the
_with a term:example : α → β → α := _ example : (α → β → γ) → β → α → γ := _ example : (α → β) → (γ → α) → γ → β := _ example : ((α → β) → α) → (α → β) → β := _
-
Explain why the type
\alpha \to \beta(with\alphaand\betadistinct type variables) is not inhabited. What about((\alpha \to \beta) \to \alpha) \to \alpha(Peirce's law)? Relate your answer to intuitionistic logic. -
Define in Lean a function
twice : (ℕ → ℕ) → ℕ → ℕthat applies a function twice, and use#evalto computetwice (fun n ↦ n * 3) 2.