Jeremy AvigadLeonardo de MouraSoonho KongSebastian Ullrich
with contributions from the Lean Community
This version of the text assumes you’re using Lean 4 (specifically 4.33.0). See the
Quickstart section of
the Lean documentation to install Lean. The first version of this book was
written for Lean 2, and the Lean 3 version is available
here.
Formal verification involves the use of logical and computational methods to establish claims that are expressed in
precise mathematical terms. These can include ordinary mathematical theorems, as well as claims that pieces of hardware
or software, network protocols, and mechanical and hybrid systems meet their specifications. In practice, there is not a
sharp distinction between verifying a piece of mathematics and verifying the correctness of a system: formal
verification requires describing hardware and software systems in mathematical terms, at which point establishing claims
as to their correctness becomes a form of theorem proving. Conversely, the proof of a mathematical theorem may require a
lengthy computation, in which case verifying the truth of the theorem requires verifying that the computation does what
it is supposed to do.
The gold standard for supporting a mathematical claim is to provide a proof, and twentieth-century developments in logic
show most if not all conventional proof methods can be reduced to a small set of axioms and rules in any of a number of
foundational systems. With this reduction, there are two ways that a computer can help establish a claim: it can help
find a proof in the first place, and it can help verify that a purported proof is correct.
Automated theorem proving focuses on the “finding” aspect. Resolution theorem provers, tableau theorem provers, fast
satisfiability solvers, and so on provide means of establishing the validity of formulas in propositional and
first-order logic. Other systems provide search procedures and decision procedures for specific languages and domains,
such as linear or nonlinear expressions over the integers or the real numbers. Architectures like SMT ("satisfiability
modulo theories”) combine domain-general search methods with domain-specific procedures. Computer algebra systems and
specialized mathematical software packages provide means of carrying out mathematical computations, establishing
mathematical bounds, or finding mathematical objects. A calculation can be viewed as a proof as well, and these systems,
too, help establish mathematical claims.
Automated reasoning systems strive for power and efficiency, often at the expense of guaranteed soundness. Such systems
can have bugs, and it can be difficult to ensure that the results they deliver are correct. In contrast, interactive
theorem proving focuses on the “verification” aspect of theorem proving, requiring that every claim is supported by a
proof in a suitable axiomatic foundation. This sets a very high standard: every rule of inference and every step of a
calculation has to be justified by appealing to prior definitions and theorems, all the way down to basic axioms and
rules. In fact, most such systems provide fully elaborated “proof objects” that can be communicated to other systems and
checked independently. Constructing such proofs typically requires much more input and interaction from users, but it
allows you to obtain deeper and more complex proofs.
The Lean Theorem Prover aims to bridge the gap between interactive and automated theorem proving, by situating
automated tools and methods in a framework that supports user interaction and the construction of fully specified
axiomatic proofs. The goal is to support both mathematical reasoning and reasoning about complex systems, and to verify
claims in both domains.
Lean's underlying logic has a computational interpretation, and Lean can be viewed equally well as a programming
language. More to the point, it can be viewed as a system for writing programs with a precise semantics, as well as
reasoning about the functions that the programs compute. Lean also has mechanisms to serve as its own metaprogramming
language, which means that you can implement automation and extend the functionality of Lean using Lean itself. These
aspects of Lean are described in the free online book, Functional Programming in Lean, though computational
aspects of the system will make an appearance here.
The Lean project was launched by Leonardo de Moura at Microsoft Research Redmond in 2013. It is an ongoing, long-term
effort, and much of the potential for automation will be realized only gradually over time. Lean is released under the
Apache 2.0 license, a permissive open source license that permits others to use and extend the code and
mathematical libraries freely.
To install Lean in your computer consider using the Quickstart instructions. The Lean source code, and instructions for building Lean, are available at
https://github.com/leanprover/lean4/.
This tutorial describes the current version of Lean, known as Lean 4.
This book is designed to teach you to develop and verify proofs in Lean. Much of the background information you will
need in order to do this is not specific to Lean at all. To start with, you will learn the logical system that Lean is
based on, a version of dependent type theory that is powerful enough to prove almost any conventional mathematical
theorem, and expressive enough to do it in a natural way. More specifically, Lean is based on a version of a system
known as the Calculus of Constructions with inductive types. Lean can not only define mathematical objects and express
mathematical assertions in dependent type theory, but it also can be used as a language for writing proofs.
Because fully detailed axiomatic proofs are so complicated, the challenge of theorem proving is to have the computer
fill in as many of the details as possible. You will learn various methods to support this in dependent type
theory. For example, term rewriting, and Lean's automated methods for simplifying terms and
expressions automatically. Similarly, methods of elaboration and type inference, which can be used to support
flexible forms of algebraic reasoning.
Finally, you will learn about features that are specific to Lean, including the language you use to communicate
with the system, and the mechanisms Lean offers for managing complex theories and data.
Throughout the text you will find examples of Lean code like the one below:
Next to every code example in this book, you will see a button that reads “Copy to clipboard”.
Pressing the button copies the example with enough surrounding context to make the code compile correctly.
You can paste the example code into VS Code and modify the examples, and Lean will check the results and provide feedback continuously as you type.
We recommend running the examples and experimenting with the code on your own as you work through the chapters that follow.
You can open this book in VS Code by using the command “Lean 4: Docs: Show Documentation Resources” and selecting “Theorem Proving in Lean 4” in the tab that opens.
This tutorial is an open access project maintained on Github. Many people have contributed to the effort, providing
corrections, suggestions, examples, and text. We are grateful to Ulrik Buchholz, Kevin Buzzard, Mario Carneiro, Nathan
Carter, Eduardo Cavazos, Amine Chaieb, Joe Corneli, William DeMeo, Marcus Klaas de Vries, Ben Dyer, Gabriel Ebner,
Anthony Hart, Simon Hudon, Sean Leather, Assia Mahboubi, Gihan Marasingha, Patrick Massot, Christopher John Mazey,
Sebastian Ullrich, Floris van Doorn, Daniel Velleman, Théo Zimmerman, Paul Chisholm, Chris Lovett, and Siddhartha Gadgil for their contributions. Please see lean prover and lean community for an up to date list
of our amazing contributors.
Dependent type theory is a powerful and expressive language, allowing
you to express complex mathematical assertions, write complex hardware
and software specifications, and reason about both of these in a
natural and uniform way. Lean is based on a version of dependent type
theory known as the Calculus of Constructions, with a countable
hierarchy of non-cumulative universes and inductive types. By the end
of this chapter, you will understand much of what this means.
“Type theory” gets its name from the fact that every expression has an
associated type. For example, in a given context, x + 0 may
denote a natural number and f may denote a function on the natural
numbers. For those who like precise definitions, a Lean natural number
is an arbitrary-precision unsigned integer.
Here are some examples of how you can declare objects in Lean and
check their types.
/- Define some constants. -/defm:Nat:=1-- m is a natural numberdefn:Nat:=0defb1:Bool:=true-- b1 is a Booleandefb2:Bool:=false/- Check their types. -/m:Nat#checkm
Any text between /- and -/ constitutes a comment block that is
ignored by Lean. Similarly, two dashes -- indicate that the rest of
the line contains a comment that is also ignored. Comment blocks can
be nested, making it possible to “comment out” chunks of code, just as
in many programming languages.
The def keyword declares new constant symbols into the
working environment. In the example above, defm:Nat:=1
defines a new constant m of type Nat whose value is 1.
The #check command asks Lean to report their
types; in Lean, auxiliary commands that query the system for
information typically begin with the hash (#) symbol.
The #eval command asks Lean to evaluate the given expression.
You should try
declaring some constants and type checking some expressions on your
own. Declaring new objects in this manner is a good way to experiment
with the system.
What makes simple type theory powerful is that you can build new types
out of others. For example, if a and b are types, a->b
denotes the type of functions from a to b, and a×b
denotes the type of pairs consisting of an element of a paired
with an element of b, also known as the Cartesian product. Note
that × is a Unicode symbol. The judicious use of Unicode improves
legibility, and all modern editors have great support for it. In the
Lean standard library, you often see Greek letters to denote types,
and the Unicode symbol → as a more compact version of ->.
Once again, you should try some examples on your own.
Let's take a look at some basic syntax. You can enter the Unicode
arrow → by typing \to or \r or \->. You can also use the
ASCII alternative ->, so the expressions Nat->Nat and Nat→Nat
mean the same thing. Both expressions denote the type of
functions that take a natural number as input and return a natural
number as output. The Unicode symbol × for the Cartesian product
is entered as \times. You will generally use lower-case Greek
letters like α, β, and γ to range over types. You can
enter these particular ones with \a, \b, and \g.
There are a few more things to notice here. First, the application of
a function f to a value x is denoted fx (e.g., Nat.succ2).
Second, when writing type expressions, arrows associate to the right; for
example, the type of Nat.add is Nat→Nat→Nat which is equivalent
to Nat→(Nat→Nat). Thus you can
view Nat.add as a function that takes a natural number and returns
another function that takes a natural number and returns a natural
number. In type theory, this is generally more convenient than
writing Nat.add as a function that takes a pair of natural numbers as
input and returns a natural number as output. For example, it allows
you to “partially apply” the function Nat.add. The example above shows
that Nat.add3 has type Nat→Nat, that is, Nat.add3 returns a
function that “waits” for a second argument, n, which is then
equivalent to writing Nat.add3n.
You have seen that if you have m : Nat and n : Nat, then
(m,n) denotes the ordered pair of m and n which is of
type Nat×Nat. This gives you a way of creating pairs of natural
numbers. Conversely, if you have p : Nat×Nat, then you can write
p.1:Nat and p.2:Nat. This gives you a way of extracting
its two components.
One way in which Lean's dependent type theory extends simple type
theory is that types themselves—entities like Nat and Bool—are first-class citizens, which is to say that they themselves are
objects. For that to be the case, each of them also has to have a
type.
You have actually come up against one of the most subtle aspects of
Lean's typing system. Lean's underlying foundation has an infinite
hierarchy of types:
Think of Type0 as a universe of “small” or “ordinary” types.
Type1 is then a larger universe of types, which contains Type0
as an element, and Type2 is an even larger universe of types,
which contains Type1 as an element. The list is infinite:
there is a Typen for every natural number n. Type is
an abbreviation for Type0:
The following table may help concretize the relationships being discussed.
Movement along the x-axis represents a change in the universe, while movement
along the y-axis represents a change in what is sometimes referred to as
“degree”.
Some operations, however, need to be polymorphic over type
universes. For example, Listα should make sense for any type
α, no matter which type universe α lives in. This explains the
type signature of the function List:
Here u is a variable ranging over type levels. The output of the
#check command means that whenever α has type Typeu,
Listα also has type Typeu. The function Prod is
similarly polymorphic:
Creating a function from another expression is a process known as
lambda abstraction. Suppose you have the variable x : α and you can
construct an expression t : β, then the expression fun(x:α)=>t,
or, equivalently, λ(x:α)=>t, is an object of type α→β. Think of
this as the function from α to β which maps
any value x to the value t.
Lean interprets the final three examples as the same expression; in
the last expression, Lean infers the type of x and y from the
expression ifnotythenx+1elsex+2.
Some mathematically common examples of operations of functions can be
described in terms of lambda abstraction:
funx=>true : Nat→Bool#checkfunVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x:Nat=>true
Think about what these expressions mean. The expression
funx:Nat=>x denotes the identity function on Nat, the
expression funx:Nat=>true denotes the constant function that
always returns true, and funx:Nat=>g(fx) denotes the
composition of f and g. You can, in general, leave off the
type annotation and let Lean infer it for you. So, for example, you
can write funx=>g(fx) instead of funx:Nat=>g(fx).
You can pass functions as parameters and by giving them names f
and g you can then use those functions in the implementation:
The last expression, for example, denotes the function that takes
three types, α, β, and γ, and two functions, g:β→γ
and f:α→β, and returns the composition of g and f.
(Making sense of the type of this function requires an understanding
of dependent products, which will be explained below.)
The general form of a lambda expression is fun(x:α)=>t, where
the variable x is a “bound variable”: it is really a placeholder,
whose “scope” does not extend beyond the expression t. For
example, the variable b in the expression fun(b:β)(x:α)=>b
has nothing to do with the constant b declared earlier. In fact,
the expression denotes the same function as fun(u:β)(z:α)=>u.
Formally, expressions that are the same up to a renaming of bound
variables are called alpha equivalent, and are considered “the
same.” Lean recognizes this equivalence.
Notice that applying a term t : α→β to a term s : α yields
an expression ts:β. Returning to the previous example and
renaming bound variables for clarity, notice the types of the
following expressions:
(funx=>true)1 : Bool#check(funVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x:Nat=>true)1
As expected, the expression (funx:Nat=>x)1 has type Nat.
In fact, more should be true: applying the expression (funx:Nat=>x) to
1 should “return” the value 1. And, indeed, it does:
true#eval(funVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x:Nat=>true)1
true
You will see later how these terms are evaluated. For now, notice that
this is an important feature of dependent type theory: every term has
a computational behavior, and supports a notion of normalization. In
principle, two terms that reduce to the same value are called
definitionally equal. They are considered “the same” by Lean's type
checker, and Lean does its best to recognize and support these
identifications.
Lean is a complete programming language. It has a compiler that
generates a binary executable and an interactive interpreter. You can
use the command #eval to execute expressions, and it is the
preferred way of testing your functions.
This might look more familiar to you if you know how functions work in
other programming languages. The name double is defined as a
function that takes an input parameter x of type Nat, where the
result of the call is x+x, so it is returning type Nat. You
can then invoke this function using:
The general form of a definition is def foo : α := bar where
α is the type returned from the expression bar. Lean can
usually infer the type α, but it is often a good idea to write it
explicitly. This clarifies your intention, and Lean will flag an
error if the right-hand side of the definition does not have a matching
type.
The right hand side bar can be any expression, not just a lambda.
So def can also be used to simply name a value like this:
defpi:=3.141592654
def can take multiple input parameters. Let's create one
that adds two natural numbers:
You can also define a function that takes another function as input.
The following calls a given function twice passing the output of the
first invocation to the second:
Now to get a bit more abstract, you can also specify arguments that
are like type parameters:
defcompose(αβγ:Type)(g:β→γ)(f:α→β)(x:α):γ:=g(fx)
This means compose is a function that takes any two functions as input
arguments, so long as those functions each take only one input.
The type algebra β→γ and α→β means it is a requirement
that the type of the output of the second function must match the
type of the input to the first function—which makes sense, otherwise
the two functions would not be composable.
compose also takes a 3rd argument of type α which
it uses to invoke the second function (locally named f) and it
passes the result of that function (which is type β) as input to the
first function (locally named g). The first function returns a type
γ so that is also the return type of the compose function.
compose is also very general in that it works over any type
αβγ. This means compose can compose just about any 2 functions
so long as they each take one parameter, and so long as the type of
output of the second matches the input of the first. For example:
While Lean fundamentally considers a defined name to be the same as its unfolding, not all names are unfolded in all contexts.
Take this example that defines Natural as an alternative name for Nat:
defNatural:=Nat
defNatural:=Nat
deffive:Natural:=failed to synthesize instance of type classOfNatNatural5numerals are polymorphic in Lean, but the numeral `5` cannot be used in a context where the expected type isNaturaldue to the absence of the instance aboveHint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.5
failed to synthesize instance of type classOfNatNatural5numerals are polymorphic in Lean, but the numeral `5` cannot be used in a context where the expected type isNaturaldue to the absence of the instance aboveHint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
When a name is defined using def, it is called semireducible: Lean will unfold it when absolutely necessary to establish that two terms are definitionally equal, but most automated features will leave references to the defined name untouched.
Lean also allows you to introduce “local” definitions using the
let keyword. The expression leta:=t1;t2 is
definitionally equal to the result of replacing every occurrence of
a in t2 by t1.
Notice that the meaning of the expression leta:=t1;t2 is very
similar to the meaning of (funa=>t2)t1, but the two are not
the same. In the first expression, you should think of every instance
of a in t2 as a syntactic abbreviation for t1. In the
second expression, a is a variable, and the expression
funa=>t2 has to make sense independently of the value of a.
The let construct is a stronger means of abbreviation, and there
are expressions of the form leta:=t1;t2 that cannot be
expressed as (funa=>t2)t1. As an exercise, try to understand
why the definition of foo below type checks, but the definition of
bar does not.
deffoo:=leta:=Nat;funx:a=>x+2/-
def bar := (fun a => fun x : a => x + 2) Nat
-/
Printing them out shows that all three groups of definitions have
exactly the same effect.
The variable command instructs Lean to insert the declared
variables as bound variables in definitions that refer to them by
name. Lean is smart enough to figure out which variables are used
explicitly or implicitly in a definition. You can therefore proceed as
though α, β, γ, g, f, h, and x are fixed
objects when you write your definitions, and let Lean abstract the
definitions for you automatically.
When declared in this way, a variable stays in scope until the end of
the file you are working on. Sometimes, however, it is useful to limit
the scope of a variable. For that purpose, Lean provides the notion of
a section:
When the section is closed, the variables go out of scope, and cannot
be referenced any more.
You do not have to indent the lines within a section. Nor do you have
to name a section, which is to say, you can use an anonymous
section / end pair. If you do name a section, however, you
have to close it using the same name. Sections can also be nested,
which allows you to declare new variables incrementally.
When you declare that you are working in the namespace Foo, every
identifier you declare has a full name with prefix “Foo.”. Within
the namespace, you can refer to identifiers by their shorter names,
but once you end the namespace, you have to use the longer names.
Unlike section, namespaces require a name. There is only one
anonymous namespace at the root level.
The open command brings the shorter names into the current
context. Often, when you import a module, you will want to open one or
more of the namespaces it contains, to have access to the short
identifiers. But sometimes you will want to leave this information
protected by a fully qualified name, for example, when they conflict
with identifiers in another namespace you want to use. Thus namespaces
give you a way to manage names in your working environment.
For example, Lean groups definitions and theorems involving lists into
a namespace List.
Like sections, nested namespaces have to be closed in the order they
are opened. Namespaces and sections serve different purposes:
namespaces organize data and sections declare variables for insertion
in definitions. Sections are also useful for delimiting the scope of
commands such as set_option and open.
In many respects, however, a namespace ... end block behaves the
same as a section ... end block. In particular, if you use the
variable command within a namespace, its scope is limited to the
namespace. Similarly, if you use an open command within a
namespace, its effects disappear when the namespace is closed.
The short explanation is that types can depend on parameters. You
have already seen a nice example of this: the type Listα depends
on the argument α, and this dependence is what distinguishes
ListNat and ListBool. For another example, consider the
type Vectorαn, the type of vectors of elements of α of
length n. This type depends on two parameters: the type of the
elements in the vector (α : Type) and the length of the vector
n : Nat.
Suppose you wish to write a function cons which inserts a new
element at the head of a list. What type should cons have? Such a
function is polymorphic: you expect the cons function for
Nat, Bool, or an arbitrary type α to behave the same way.
So it makes sense to take the type to be the first argument to
cons, so that for any type, α, consα is the insertion
function for lists of type α. In other words, for every α,
consα is the function that takes an element a : α and a list
as : Listα, and returns a new list, so you have consαaas:Listα.
It is clear that consα should have type α→Listα→Listα.
But what type should cons have? A first guess might be
Type→α→Listα→Listα, but, on reflection, this does not make
sense: the α in this expression does not refer to anything,
whereas it should refer to the argument of type Type. In other
words, assumingα : Type is the first argument to the function,
the type of the next two elements are α and Listα. These
types vary depending on the first argument, α.
This is an instance of a dependent function type, or dependent
arrow type. Given α : Type and β : α→Type, think of β
as a family of types over α, that is, a type βa for each
a : α. In that case, the type (a:α)→βa denotes the type
of functions f with the property that, for each a : α, fa
is an element of βa. In other words, the type of the value
returned by f depends on its input.
Notice that (a:α)→β makes sense for any expression β : Type.
When the value of β depends on a (as does, for
example, the expression βa in the previous paragraph),
(a:α)→β denotes a dependent function type. When β doesn't
depend on a, (a:α)→β is no different from the type
α→β. Indeed, in dependent type theory (and in Lean), α→β
is just notation for (a:α)→β when β does not depend on a.
Returning to the example of lists, you can use the command #check to
inspect the type of the following List functions. The @ symbol
and the difference between the round and curly braces will be
explained momentarily.
Just as dependent function types (a:α)→βa generalize the
notion of a function type α→β by allowing β to depend on
a, dependent Cartesian product types (a:α)×βa generalize
the Cartesian product α × β in the same way. Dependent products
are also called sigma types, and you can also write them as
Σa:α,βa. You can use ⟨a,b⟩ or Sigma.mkab to create a
dependent pair. The ⟨ and ⟩ characters may be typed with
\langle and \rangle or \< and \>, respectively.
Because the constructors are polymorphic over types, we have to insert
the type Nat as an argument repeatedly. But this information is
redundant: one can infer the argument α in
Lst.consNat5(Lst.nilNat) from the fact that the second argument, 5, has
type Nat. One can similarly infer the argument in Lst.nilNat, not
from anything else in that expression, but from the fact that it is
sent as an argument to the function Lst.cons, which expects an element
of type Lstα in that position.
This is a central feature of dependent type theory: terms carry a lot
of information, and often some of that information can be inferred
from the context. In Lean, one uses an underscore, _, to specify
that the system should fill in the information automatically. This is
known as an “implicit argument.”
It is still tedious, however, to type all these underscores. When a
function takes an argument that can generally be inferred from
context, Lean allows you to specify that this argument should, by
default, be left implicit. This is done by putting the arguments in
curly braces, as follows:
The makes the first argument to ident implicit. Notationally,
this hides the specification of the type, making it look as though
ident simply takes an argument of any type. In fact, the function
id is defined in the standard library in exactly this way. We have
chosen a nontraditional name here only to avoid a clash of names.
Variables can also be specified as implicit when they are declared with
the variable command:
This definition of ident here has the same effect as the one
above.
Lean has very complex mechanisms for instantiating implicit arguments,
and we will see that they can be used to infer function types,
predicates, and even proofs. The process of instantiating these
“holes,” or “placeholders,” in a term is often known as
elaboration. The presence of implicit arguments means that at times
there may be insufficient information to fix the meaning of an
expression precisely. An expression like id or List.nil is
said to be polymorphic, because it can take on different meanings in
different contexts.
One can always specify the type T of an expression e by
writing (e:T). This instructs Lean's elaborator to use the value
T as the type of e when trying to resolve implicit
arguments. In the second pair of examples below, this mechanism is
used to specify the desired types of the expressions id and
List.nil:
Numerals are overloaded in Lean, but when the type of a numeral cannot
be inferred, Lean assumes, by default, that it is a natural number. So
the expressions in the first two #check commands below are
elaborated in the same way, whereas the third #check command
interprets 2 as an integer.
Sometimes, however, we may find ourselves in a situation where we have
declared an argument to a function to be implicit, but now want to
provide the argument explicitly. If foo is such a function, the
notation @foo denotes the same function with all the arguments
made explicit.
Notice that now the first #check command gives the type of the
identifier, id, without inserting any placeholders. Moreover, the
output indicates that the first argument is implicit.
By now, you have seen some ways of defining objects and functions in
Lean. In this chapter, we will begin to explain how to write
mathematical assertions and proofs in the language of dependent type
theory as well.
One strategy for proving assertions about objects defined in the
language of dependent type theory is to layer an assertion language
and a proof language on top of the definition language. But there is
no reason to multiply languages in this way: dependent type theory is
flexible and expressive, and there is no reason we cannot represent
assertions and proofs in the same general framework.
For example, we could introduce a new type, Prop, to represent
propositions, and introduce constructors to build new propositions
from others.
In addition to axioms, however, we would also need rules to build new
proofs from old ones. For example, in many proof systems for
propositional logic, we have the rule of modus ponens:
From a proof of Impliespq and a proof of p, we obtain a proof of q.
This approach would provide us with a reasonable way of building assertions and proofs.
Determining that an expression t is a correct proof of assertion p would then
simply be a matter of checking that t has type Proofp.
Some simplifications are possible, however. To start with, we can
avoid writing the term Proof repeatedly by conflating Proofp
with p itself. In other words, whenever we have p : Prop, we
can interpret p as a type, namely, the type of its proofs. We can
then read t : p as the assertion that t is a proof of p.
Moreover, once we make this identification, the rules for implication
show that we can pass back and forth between Impliespq and
p→q. In other words, implication between propositions p and q
corresponds to having a function that takes any element of p to an
element of q. As a result, the introduction of the connective
Implies is entirely redundant: we can use the usual function space
constructor p→q from dependent type theory as our notion of
implication.
This is the approach followed in the Calculus of Constructions, and
hence in Lean as well. The fact that the rules for implication in a
proof system for natural deduction correspond exactly to the rules
governing abstraction and application for functions is an instance of
the Curry-Howard isomorphism, sometimes known as the
propositions-as-types paradigm. In fact, the type Prop is
syntactic sugar for Sort0, the very bottom of the type hierarchy
described in the last chapter. Moreover, Typeu is also just
syntactic sugar for Sort(u+1). Prop has some special
features, but like the other type universes, it is closed under the
arrow constructor: if we have pq : Prop, then p→q:Prop.
There are at least two ways of thinking about propositions as
types. To some who take a constructive view of logic and mathematics,
this is a faithful rendering of what it means to be a proposition: a
proposition p represents a sort of data type, namely, a
specification of the type of data that constitutes a proof. A proof of
p is then simply an object t : p of the right type.
Those not inclined to this ideology can view it, rather, as a simple
coding trick. To each proposition p we associate a type that is
empty if p is false and has a single element, say *, if p
is true. In the latter case, let us say that (the type associated
with) p is inhabited. It just so happens that the rules for
function application and abstraction can conveniently help us keep
track of which elements of Prop are inhabited. So constructing an
element t : p tells us that p is indeed true. You can think of
the inhabitant of p as being the “fact that p is true.” A
proof of p→q uses “the fact that p is true” to obtain “the
fact that q is true.”
Indeed, if p : Prop is any proposition, Lean's kernel treats any
two elements t1t2 : p as being definitionally equal, much the
same way as it treats (fun x => t) s and t[s/x] as
definitionally equal. This is known as proof irrelevance, and is
consistent with the interpretation in the last paragraph. It means
that even though we can treat proofs t : p as ordinary objects in
the language of dependent type theory, they carry no information
beyond the fact that p is true.
The two ways we have suggested thinking about the
propositions-as-types paradigm differ in a fundamental way. From the
constructive point of view, proofs are abstract mathematical objects
that are denoted by suitable expressions in dependent type
theory. In contrast, if we think in terms of the coding trick
described above, then the expressions themselves do not denote
anything interesting. Rather, it is the fact that we can write them
down and check that they are well-typed that ensures that the
proposition in question is true. In other words, the expressions
themselves are the proofs.
In the exposition below, we will slip back and forth between these two
ways of talking, at times saying that an expression “constructs” or
“produces” or “returns” a proof of a proposition, and at other times
simply saying that it “is” such a proof. This is similar to the way
that computer scientists occasionally blur the distinction between
syntax and semantics by saying, at times, that a program “computes” a
certain function, and at other times speaking as though the program
“is” the function in question.
In any case, all that really matters is the bottom line. To formally
express a mathematical assertion in the language of dependent type
theory, we need to exhibit a term p : Prop. To prove that
assertion, we need to exhibit a term t : p. Lean's task, as a
proof assistant, is to help us to construct such a term, t, and to
verify that it is well-formed and has the correct type.
In the propositions-as-types paradigm, theorems involving only →
can be proved using lambda abstraction and application. In Lean, the
theorem command introduces a new theorem:
Compare this proof to the expression funx:α=>funy:β=>x
of type α→β→α, where α and β are data types.
This describes the function that takes arguments x and y
of type α and β, respectively, and returns x.
The proof of t1 has the same form, the only difference being that
p and q are elements of Prop rather than Type.
Intuitively, our proof of
p→q→p assumes p and q are true, and uses the first
hypothesis (trivially) to establish that the conclusion, p, is
true.
Note that the theorem command is really a version of the
def command: under the propositions and types
correspondence, proving the theorem p→q→p is really the same
as defining an element of the associated type. To the kernel type
checker, there is no difference between the two.
There are a few pragmatic differences between definitions and
theorems, however. In normal circumstances, it is never necessary to
unfold the “definition” of a theorem; by proof irrelevance, any two
proofs of that theorem are definitionally equal. Once the proof of a
theorem is complete, typically we only need to know that the proof
exists; it doesn't matter what the proof is. In light of that fact,
Lean tags proofs as irreducible, which serves as a hint to the
parser (more precisely, the elaborator) that there is generally no
need to unfold them when processing a file. In fact, Lean is generally
able to process and check proofs in parallel, since assessing the
correctness of one proof does not require knowing the details of
another. Additionally, section variables
that are referred to in the body of a definition are automatically added as
parameters, but only the variables referred to in a theorem's type are added.
This is because the way in which a statement is proved should not influence
the statement that is being proved.
As with definitions, the #print command will show you the proof of
a theorem:
Notice that the lambda abstractions hp:p and hq:q can be
viewed as temporary assumptions in the proof of t1. Lean also
allows us to specify the type of the final term hp, explicitly,
with a show statement:
Adding such extra information can improve the clarity of a proof and
help detect errors when writing a proof. The show command does
nothing more than annotate the type, and, internally, all the
presentations of t1 that we have seen produce the same term.
As with ordinary definitions, we can move the lambda-abstracted
variables to the left of the colon:
The axiom declaration postulates the existence of an
element of the given type and may compromise logical consistency. For
example, we can use it to postulate that the empty type False has an
element:
axiomunsound:False-- Everything follows from falsetheoremex:1=0:=False.elimunsound
Declaring an “axiom” hp : p is tantamount to declaring that p
is true, as witnessed by hp. Applying the theorem
t1 : p→q→p to the fact hp : p that p is true yields the theorem
t1hp:q→p.
Recall that we can also write theorem t1 as follows:
The type of t1 is now ∀{pq:Prop},p→q→p. We can read
this as the assertion “for every pair of propositions pq, we have
p→q→p.” For example, we can move all parameters to the right
of the colon:
If p and q have been declared as variables, Lean will
generalize them for us automatically:
variable{pq:Prop}theoremt1:p→q→p:=fun(hp:p)(Variable name `hq` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_hqNote: This linter can be disabled with `set_option linter.unusedVariables false`hq:q)=>hp
When we generalize t1 in such a way, we can then apply it to
different pairs of propositions, to obtain different instances of the
general theorem.
The order of operations is as follows: unary negation ¬ binds most
strongly, then ∧, then ∨, then →, and finally ↔. For
example, a∧b→c∨d∧e means (a∧b)→(c∨(d∧e)).
Remember that → associates to the right (nothing changes
now that the arguments are elements of Prop, instead of some other
Type), as do the other binary connectives. So if we have
pqr : Prop, the expression p→q→r reads “if p, then if q,
then r.” This is just the “curried” form of p∧q→r.
In the last chapter we observed that lambda abstraction can be viewed
as an “introduction rule” for →. In the current setting, it shows
how to “introduce” or establish an implication. Application can be
viewed as an “elimination rule,” showing how to “eliminate” or use an
implication in a proof. The other propositional connectives are
defined in Lean's library, and are automatically imported. Each connective
comes with its canonical introduction and elimination rules.
The expression And.introh1h2 builds a proof of p∧q using
proofs h1 : p and h2 : q. It is common to describe
And.intro as the and-introduction rule. In the next example we
use And.intro to create a proof of p→q→p∧q.
The example command states a theorem without naming it or storing
it in the permanent context. Essentially, it just checks that the
given term has the indicated type. It is convenient for illustration,
and we will use it often.
The expression And.lefth creates a proof of p from a proof
h : p∧q. Similarly, And.righth is a proof of q. They
are commonly known as the left and right and-elimination rules.
Notice that and-introduction and and-elimination are similar to the
pairing and projection operations for the Cartesian product. The
difference is that given hp : p and hq : q, And.introhphq has type
p∧q:Prop, while given a : α and b : β, Prod.mkab has type
α×β:Type. Prod cannot be used with Props, and And cannot be used with Types.
The similarity between ∧ and × is another instance
of the Curry-Howard isomorphism, but in contrast to implication and
the function space constructor, ∧ and × are treated separately
in Lean. With the analogy, however, the proof we have just constructed
is similar to a function that swaps the elements of a pair.
We will see in Structures and Records that certain
types in Lean are structures, which is to say, the type is defined
with a single canonical constructor which builds an element of the
type from a sequence of suitable arguments. For every pq : Prop,
p∧q is an example: the canonical way to construct an element is
to apply And.intro to suitable arguments hp : p and
hq : q. Lean allows us to use anonymous constructor notation
⟨arg1, arg2, ...⟩ in situations like these, when the relevant type is an
inductive type and can be inferred from the context. In particular, we
can often write ⟨hp,hq⟩ instead of And.introhphq:
These angle brackets are obtained by typing \< and \>, respectively.
Lean provides another useful syntactic gadget. Given an expression
e of an inductive type Foo (possibly applied to some
arguments), the notation e.bar is shorthand for Foo.bare.
This provides a convenient way of accessing functions without opening
a namespace. For example, the following two expressions mean the same
thing:
As a result, given h : p∧q, we can write h.left for
And.lefth and h.right for And.righth. We can therefore
rewrite the sample proof above conveniently as follows:
There is a fine line between brevity and obfuscation, and omitting
information in this way can sometimes make a proof harder to read. But
for straightforward constructions like the one above, when the type of
h and the goal of the construction are salient, the notation is
clean and effective.
It is common to iterate constructions like “And.” Lean also allows you
to flatten nested constructors that associate to the right, so that
these two proofs are equivalent:
The expression Or.intro_leftqhp creates a proof of p∨q
from a proof hp : p. Similarly, Or.intro_rightphq creates a
proof for p∨q using a proof hq : q. These are the left and
right or-introduction rules.
The or-elimination rule is slightly more complicated. The idea is
that we can prove r from p∨q, by showing that r follows
from p and that r follows from q. In other words, it is a
proof by cases. In the expression Or.elimhpqhprhqr, Or.elim
takes three arguments, hpq : p∨q, hpr : p→r and
hqr : q→r, and produces a proof of r. In the following example, we use
Or.elim to prove p∨q→q∨p.
In most cases, the first argument of Or.intro_right and
Or.intro_left can be inferred automatically by Lean. Lean
therefore provides Or.inr and Or.inl which can be viewed as
shorthand for Or.intro_right_ and Or.intro_left_. Thus the
proof term above could be written more concisely:
Notice that there is enough information in the full expression for
Lean to infer the types of hp and hq as well. But using the
type annotations in the longer version makes the proof more readable,
and can help catch and debug errors.
Because Or has two constructors, we cannot use anonymous
constructor notation. But we can still write h.elim instead of
Or.elimh:
Negation, ¬p, is actually defined to be p→False, so we
obtain ¬p by deriving a contradiction from p. Similarly, the
expression hnphp produces a proof of False from hp : p
and hnp : ¬p. The next example uses both these rules to produce a
proof of (p→q)→¬q→¬p. (The symbol ¬ is produced by
typing \not or \neg.)
The connective False has a single elimination rule,
False.elim, which expresses the fact that anything follows from a
contradiction. This rule is sometimes called ex falso (short for ex
falso sequitur quodlibet), or the principle of explosion.
The arbitrary fact, q, that follows from falsity is an implicit
argument in False.elim and is inferred automatically. This
pattern, deriving an arbitrary fact from contradictory hypotheses, is
quite common, and is represented by absurd.
Incidentally, just as False has only an elimination rule, True
has only an introduction rule, True.intro:True. In other words,
True is simply true, and has a canonical proof, True.intro.
The expression Iff.introh1h2 produces a proof of p↔q from
h1 : p→q and h2 : q→p. The expression Iff.mph
produces a proof of p→q from h : p↔q. Similarly,
Iff.mprh produces a proof of q→p from h : p↔q. Here is a proof
of p∧q↔q∧p:
We can use the anonymous constructor notation to construct a proof of
p↔q from proofs of the forward and backward directions, and we
can also use . notation with mp and mpr. The previous
examples can therefore be written concisely as follows:
This is a good place to introduce another device Lean offers to help
structure long proofs, namely, the have construct, which
introduces an auxiliary subgoal in a proof. Here is a small example,
adapted from the last section:
Internally, the expression haveh:p:=s;t produces the term
(fun(h:p)=>t)s. In other words, s is a proof of p,
t is a proof of the desired conclusion assuming h:p, and the
two are combined by a lambda abstraction and application. This simple
device is extremely useful when it comes to structuring long proofs,
since we can use intermediate have's as stepping stones leading to
the final goal.
Lean also supports a structured way of reasoning backwards from a
goal, which models the “suffices to show” construction in ordinary
mathematics. The next example simply permutes the last two lines in
the previous proof.
Writing sufficeshq:q leaves us with two goals. First, we have
to show that it indeed suffices to show q, by proving the original
goal of q∧p with the additional hypothesis hq:q. Finally,
we have to show q.
The introduction and elimination rules we have seen so far are all
constructive, which is to say, they reflect a computational
understanding of the logical connectives based on the
propositions-as-types correspondence. Ordinary classical logic adds to
this the law of the excluded middle, p∨¬p. To use this
principle, you have to open the classical namespace.
Intuitively, the constructive “Or” is very strong: asserting p∨q
amounts to knowing which is the case. If RH represents the Riemann
hypothesis, a classical mathematician is willing to assert
RH∨¬RH, even though we cannot yet assert either disjunct.
One consequence of the law of the excluded middle is the principle of
double-negation elimination:
Double-negation elimination allows one to prove any proposition,
p, by assuming ¬p and deriving False, because that amounts
to proving ¬¬p. In other words, double-negation elimination allows
one to carry out a proof by contradiction, something which is not
generally possible in constructive logic. As an exercise, you might
try proving the converse, that is, showing that em can be proved
from dne.
The classical axioms also give you access to additional patterns of
proof that can be justified by appeal to em. For example, one can
carry out a proof by cases:
If you are not used to thinking constructively, it may take some time
for you to get a sense of where classical reasoning is used. It is
needed in the following example because, from a constructive
standpoint, knowing that p and q are not both true does not
necessarily tell you which one is false:
We will see later that there are situations in constructive logic
where principles like excluded middle and double-negation elimination
are permissible, and Lean supports the use of classical reasoning in
such contexts without relying on excluded middle.
The full list of axioms that are used in Lean to support classical
reasoning are discussed in Axioms and Computation.
Lean's standard library contains proofs of many valid statements of
propositional logic, all of which you are free to use in proofs of
your own. The following list includes a number of common identities.
The sorry identifier magically produces a proof of anything, or
provides an object of any data type at all. Of course, it is unsound
as a proof method—for example, you can use it to prove False—and
Lean produces severe warnings when files use or import theorems
which depend on it. But it is very useful for building long proofs
incrementally. Start writing the proof from the top down, using
sorry to fill in subproofs. Make sure Lean accepts the term with
all the sorry's; if not, there are errors that you need to
correct. Then go back and replace each sorry with an actual proof,
until no more remain.
Here is another useful trick. Instead of using sorry, you can use
an underscore _ as a placeholder. Recall this tells Lean that
the argument is implicit, and should be filled in automatically. If
Lean tries to do so and fails, it returns with an error message “don't
know how to synthesize placeholder,” followed by the type of
the term it is expecting, and all the objects and hypotheses available
in the context. In other words, for each unresolved placeholder, Lean
reports the subgoal that needs to be filled at that point. You can
then construct a proof by incrementally filling in these placeholders.
For reference, here are two sample proofs of validities taken from the
list above.
openClassical-- distributivityexample(pqr:Prop):p∧(q∨r)↔(p∧q)∨(p∧r):=Iff.intro(funh:p∧(q∨r)=>havehp:p:=h.leftOr.elim(h.right)(funhq:q=>show(p∧q)∨(p∧r)fromOr.inl⟨hp,hq⟩)(funhr:r=>show(p∧q)∨(p∧r)fromOr.inr⟨hp,hr⟩))(funh:(p∧q)∨(p∧r)=>Or.elimh(funhpq:p∧q=>havehp:p:=hpq.lefthavehq:q:=hpq.rightshowp∧(q∨r)from⟨hp,Or.inlhq⟩)(funhpr:p∧r=>havehp:p:=hpr.lefthavehr:r:=hpr.rightshowp∧(q∨r)from⟨hp,Or.inrhr⟩))-- an example that requires classical reasoningexample(pq:Prop):¬(p∧¬q)→(p→q):=funh:¬(p∧¬q)=>funhp:p=>showqfromOr.elim(emq)(funhq:q=>hq)(funhnq:¬q=>absurd(And.introhphnq)h)
The last chapter introduced you to methods that construct proofs of
statements involving the propositional connectives. In this chapter,
we extend the repertoire of logical constructions to include the
universal and existential quantifiers, and the equality relation.
Notice that if α is any type, we can represent a unary predicate
p on α as an object of type α→Prop. In that case, given
x : α, px denotes the assertion that p holds of
x. Similarly, an object r : α→α→Prop denotes a binary
relation on α: given xy : α, rxy denotes the assertion
that x is related to y.
The universal quantifier, ∀x:α,px is supposed to denote the
assertion that “for every x : α, px” holds. As with the
propositional connectives, in systems of natural deduction, “forall”
is governed by an introduction and elimination rule. Informally, the
introduction rule states:
Given a proof of px, in a context where x : α is arbitrary, we obtain a proof ∀x:α,px.
The elimination rule states:
Given a proof ∀x:α,px and any term t : α, we obtain a proof of pt.
As was the case for implication, the propositions-as-types
interpretation now comes into play. Remember the introduction and
elimination rules for dependent arrow types:
Given a term t of type βx, in a context where x : α is arbitrary, we have (funx:α=>t):(x:α)→βx.
The elimination rule states:
Given a term s : (x:α)→βx and any term t : α, we have st:βt.
In the case where px has type Prop, if we replace
(x:α)→βx with ∀x:α,px, we can read these as the correct rules
for building proofs involving the universal quantifier.
The Calculus of Constructions therefore identifies dependent arrow
types with forall-expressions in this way. If p is any expression,
∀x:α,p is nothing more than alternative notation for
(x:α)→p, with the idea that the former is more natural than the latter
in cases where p is a proposition. Typically, the expression p
will depend on x:α. Recall that, in the case of ordinary
function spaces, we could interpret α→β as the special case of
(x:α)→β in which β does not depend on x. Similarly, we
can think of an implication p→q between propositions as the
special case of ∀x:p,q in which the expression q does not
depend on x.
Here is an example of how the propositions-as-types correspondence gets put into practice.
As a notational convention, we give the universal quantifier the
widest scope possible, so parentheses are needed to limit the
quantifier over x to the hypothesis in the example above. The
canonical way to prove ∀y:α,py is to take an arbitrary y,
and prove py. This is the introduction rule. Now, given that
h has type ∀x:α,px∧qx, the expression hy has type
py ∧ qy. This is the elimination rule. Taking the left conjunct
gives the desired conclusion, py.
Remember that expressions which differ up to renaming of bound
variables are considered to be equivalent. So, for example, we could
have used the same variable, x, in both the hypothesis and
conclusion, and instantiated it by a different variable, z, in the
proof:
Think about what is going on here. When we instantiate trans_r at
the values abc, we end up with a proof of rab → rbc → rac.
Applying this to the “hypothesis” hab:rab, we get a proof
of the implication rbc → rac. Finally, applying it to the
hypothesis hbc yields a proof of the conclusion rac.
In situations like this, it can be tedious to supply the arguments
abc, when they can be inferred from habhbc. For that reason, it
is common to make these arguments implicit:
The advantage is that we can simply write trans_rhabhbc as a
proof of rac. A disadvantage is that Lean does not have enough
information to infer the types of the arguments in the expressions
trans_r and trans_rhab. The output of the first #check
command is r ?m.1 ?m.2 → r ?m.2 ?m.3 → r ?m.1 ?m.3, indicating
that the implicit arguments are unspecified in this case.
Here is an example of how we can carry out elementary reasoning with an equivalence relation:
To get used to using universal quantifiers, you should try some of the
exercises at the end of this section.
It is the typing rule for dependent arrow types, and the universal
quantifier in particular, that distinguishes Prop from other
types. Suppose we have α : Sorti and β : Sortj, where the
expression β may depend on a variable x : α. Then
(x:α)→β is an element of Sort(imaxij), where imax i j is the
maximum of i and j if j is not 0, and 0 otherwise.
The idea is as follows. If j is not 0, then (x:α)→β is
an element of Sort(maxij). In other words, the type of
dependent functions from α to β “lives” in the universe whose
index is the maximum of i and j. Suppose, however, that β
is of Sort0, that is, an element of Prop. In that case,
(x:α)→β is an element of Sort0 as well, no matter which
type universe α lives in. In other words, if β is a
proposition depending on α, then ∀x:α,β is again a
proposition. This reflects the interpretation of Prop as the type
of propositions rather than data, and it is what makes Propimpredicative.
The term “predicative” stems from foundational developments around the
turn of the twentieth century, when logicians such as Poincaré and
Russell blamed set-theoretic paradoxes on the “vicious circles” that
arise when we define a property by quantifying over a collection that
includes the very property being defined. Notice that if α is any
type, we can form the type α→Prop of all predicates on α
(the “power type of α”). The impredicativity of Prop means that we
can form propositions that quantify over α→Prop. In particular,
we can define predicates on α by quantifying over all predicates
on α, which is exactly the type of circularity that was once
considered problematic.
Let us now turn to one of the most fundamental relations defined in
Lean's library, namely, the equality relation. In the chapter on inductive types,
we will explain how equality is defined from the primitives of Lean's logical framework.
In the meanwhile, here we explain how to use it.
Of course, a fundamental property of equality is that it is an equivalence relation:
Reflexivity is more powerful than it looks. Recall that terms in the
Calculus of Constructions have a computational interpretation, and
that the logical framework treats terms with a common reduct as the
same. As a result, some nontrivial identities can be proved by
reflexivity:
Equality is much more than an equivalence relation, however. It has
the important property that every assertion respects the equivalence,
in the sense that we can substitute equal expressions without changing
the truth value. That is, given h1 : a=b and h2 : pa, we
can construct a proof for pb using substitution:
Eq.substh1h2.
The triangle in the second presentation is a macro built on top of
Eq.subst and Eq.symm, and you can enter it by typing \t.
The rule Eq.subst is used to define the following auxiliary rules,
which carry out more explicit substitutions. They are designed to deal
with applicative terms, that is, terms of form st. Specifically,
congrArg can be used to replace the argument, congrFun can be
used to replace the term that is being applied, and congr can be
used to replace both at once.
Note that Nat.mul_add and Nat.add_mul are alternative names
for Nat.left_distrib and Nat.right_distrib, respectively. The
properties above are stated for the natural numbers (type Nat).
Here is an example of a calculation in the natural numbers that uses
substitution combined with associativity and distributivity.
Notice that the second implicit parameter to Eq.subst, which
provides the context in which the substitution is to occur, has type
α→Prop. Inferring this predicate therefore requires an instance
of higher-order unification. In full generality, the problem of
determining whether a higher-order unifier exists is undecidable, and
Lean can at best provide imperfect and approximate solutions to the
problem. As a result, Eq.subst doesn't always do what you want it
to. The macro h▸e uses more effective heuristics for computing
this implicit parameter, and often succeeds in situations where
applying Eq.subst fails.
Because equational reasoning is so common and important, Lean provides
a number of mechanisms to carry it out more effectively. The next
section offers syntax that allow you to write calculational proofs in
a more natural and perspicuous way. But, more importantly, equational
reasoning is supported by a term rewriter, a simplifier, and other
kinds of automation. The term rewriter and simplifier are described
briefly in the next section, and then in greater detail in the next
chapter.
A calculational proof is just a chain of intermediate results that are
meant to be composed by basic principles such as the transitivity of
equality. In Lean, a calculational proof starts with the keyword
calc, and has the following syntax:
This style of writing proofs is most effective when it is used in
conjunction with the simp and rw tactics, which are
discussed in greater detail in the next chapter. For example, using
rw for rewrite, the proof above could be written
as follows:
Essentially, the rw tactic uses a given equality (which can be a
hypothesis, a theorem name, or a complex term) to “rewrite” the
goal. If doing so reduces the goal to an identity t=t, the
tactic applies reflexivity to prove it.
Rewrites can be applied sequentially, so that the proof above can be
shortened to this:
The simp tactic, instead, rewrites the goal by applying the given
identities repeatedly, in any order, anywhere they are applicable in a
term. It also uses other rules that have been previously declared to
the system, and applies commutativity wisely to avoid looping. As a
result, we can also prove the theorem as follows:
You can “teach” calc new transitivity theorems by adding new instances
of the Trans type class. Type classes are introduced later, but the following
small example demonstrates how to extend the calc notation using new Trans instances.
The example above also makes it clear that you can use calc even if you do not have an infix
notation for your relation. Lean already includes the standard Unicode notation for divisibility
(using ∣, which can be entered as \dvd or \mid), so the example above uses the ordinary
vertical bar to avoid a conflict. In practice, this is not a good idea, as it risks confusion with
the ASCII | used in the match ... with expression.
With calc, we can write the proof in the last section in a more
natural and perspicuous way.
The alternative calc notation is worth considering here. When the
first expression is taking this much space, using _ in the first
relation naturally aligns all relations:
Here the left arrow before Nat.add_assoc tells rewrite to use the
identity in the opposite direction. (You can enter it with \l or
use the ASCII equivalent, <-.) If brevity is what we are after,
both rw and simp can do the job on their own:
Finally, consider the existential quantifier, which can be written as
either existsx:α,px or ∃x:α,px. Both versions are
actually notationally convenient abbreviations for a more long-winded
expression, Exists(funx:α=>px), defined in Lean's library.
As you should by now expect, the library includes both an introduction
rule and an elimination rule. The introduction rule is
straightforward: to prove ∃x:α,px, it suffices to provide a
suitable term t and a proof of pt. Here are some examples:
Note that Exists.intro has implicit arguments: Lean has to infer
the predicate p : α→Prop in the conclusion ∃x,px. This
is not a trivial affair. For example, if we have
hg : g00=0 and write Exists.intro0hg, there are many possible values
for the predicate p, corresponding to the theorems ∃x,gxx=x,
∃x,gxx=0, ∃x,gx0=x, etc. Lean uses the
context to infer which one is appropriate. This is illustrated in the
following example, in which we set the option pp.explicit to true
to ask Lean's pretty-printer to show the implicit arguments.
We can view Exists.intro as an information-hiding operation, since
it hides the witness to the body of the assertion. The existential
elimination rule, Exists.elim, performs the opposite operation. It
allows us to prove a proposition q from ∃x:α,px, by
showing that q follows from pw for an arbitrary value
w. Roughly speaking, since we know there is an x satisfying
px, we can give it a name, say, w. If q does not mention
w, then showing that q follows from pw is tantamount to
showing that q follows from the existence of any such x. Here
is an example:
It may be helpful to compare the exists-elimination rule to the
or-elimination rule: the assertion ∃x:α,px can be thought of
as a big disjunction of the propositions pa, as a ranges over
all the elements of α. Note that the anonymous constructor
notation ⟨w,hw.right,hw.left⟩ abbreviates a nested constructor
application; we could equally well have written ⟨w, ⟨hw.right, hw.left⟩⟩.
Notice that an existential proposition is very similar to a sigma
type, as described in dependent types section. The difference is that
existential propositions are propositions, while sigma types are types.
Otherwise, they are very similar. Given a predicate p : α→Prop and a family of types β : α→Type,
for a term a : α with h : pa and h':βa, the term Exists.introah has
type (∃x:α,px):Prop, while Sigma.mkah' has type
(Σx:α,βx). The similarity between ∃ and Σ is another
instance of the Curry-Howard isomorphism.
Lean provides a more convenient way to eliminate from an existential
quantifier with the match expression:
The match expression is part of Lean's function definition system,
which provides convenient and expressive ways of defining complex
functions. Once again, it is the Curry-Howard isomorphism that allows
us to co-opt this mechanism for writing proofs as well. The match
statement “destructs” the existential assertion into the components
w and hw, which can then be used in the body of the statement
to prove the proposition. We can annotate the types used in the match
for greater clarity:
Using the various gadgets described in this chapter—the match
statement, anonymous constructors, and the rewrite tactic, we can
write this proof concisely as follows:
Just as the constructive “or” is stronger than the classical “or,” so,
too, is the constructive “exists” stronger than the classical
“exists”. For example, the following implication requires classical
reasoning because, from a constructive standpoint, knowing that it is
not the case that every x satisfies ¬p is not the same as
having a particular x that satisfies p.
What follows are some common identities involving the existential
quantifier. In the exercises below, we encourage you to prove as many
as you can. We also leave it to you to determine which are
nonconstructive, and hence require some form of classical reasoning.
Notice that the second example and the last two examples require the
assumption that there is at least one element a of type α.
Here are solutions to two of the more difficult ones:
openClassicalvariable(α:Type)(pq:α→Prop)variable(a:α)variable(r:Prop)example:(∃x,px∨qx)↔(∃x,px)∨(∃x,qx):=Iff.intro(fun⟨a,(h1:pa∨qa)⟩=>Or.elimh1(funhpa:pa=>Or.inl⟨a,hpa⟩)(funhqa:qa=>Or.inr⟨a,hqa⟩))(funh:(∃x,px)∨(∃x,qx)=>Or.elimh(fun⟨a,hpa⟩=>⟨a,(Or.inlhpa)⟩)(fun⟨a,hqa⟩=>⟨a,(Or.inrhqa)⟩))example:(∃x,px→r)↔(∀x,px)→r:=Iff.intro(fun⟨b,(hb:pb→r)⟩=>funh2:∀x,px=>showrfromhb(h2b))(funh1:(∀x,px)→r=>show∃x,px→rfrombyCases(funhap:∀x,px=>⟨a,λVariable name `h'` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_h'Note: This linter can be disabled with `set_option linter.unusedVariables false`h'=>h1hap⟩)(funhnap:¬∀x,px=>byContradiction(funhnex:¬∃x,px→r=>havehap:∀x,px:=funx=>byContradiction(funhnp:¬px=>havehex:∃x,px→r:=⟨x,(funhp=>absurdhphnp)⟩showFalsefromhnexhex)showFalsefromhnaphap)))
We have seen that keywords like fun, have, and show make
it possible to write formal proof terms that mirror the structure of
informal mathematical proofs. In this section, we discuss some
additional features of the proof language that are often convenient.
To start with, we can use anonymous have expressions to introduce an
auxiliary goal without having to label it. We can refer to the last
expression introduced in this way using the keyword this:
This tells Lean to use the assumption tactic, which, in turn,
proves the goal by finding a suitable hypothesis in the local
context. We will learn more about the assumption tactic in the
next chapter.
We can also ask Lean to fill in the proof by writing ‹p›, where
p is the proposition whose proof we want Lean to find in the
context. You can type these corner quotes using \f< and \f>,
respectively. The letter “f” is for “French,” since the Unicode
symbols can also be used as French quotation marks. In fact, the
notation is defined in Lean as follows:
This approach is more robust than using byassumption, because the
type of the assumption that needs to be inferred is given
explicitly. It also makes proofs more readable. Here is a more
elaborate example:
Keep in mind that you can use the French quotation marks in this way
to refer to anything in the context, not just things that were
introduced anonymously. Its use is also not limited to propositions,
though using it for data is somewhat odd:
You should also try to understand why the reverse implication is not derivable in the last example.
It is often possible to bring a component of a formula outside a
universal quantifier, when it does not depend on the quantified
variable. Try proving these (one direction of the second of these
requires classical logic):
Consider the “barber paradox,” that is, the claim that in a certain
town there is a (male) barber that shaves all and only the men who
do not shave themselves. Prove that this is a contradiction:
Remember that, without any parameters, an expression of type
Prop is just an assertion. Fill in the definitions of prime
and Fermat_prime below, and construct each of the given
assertions. For example, you can say that there are infinitely many
primes by asserting that for every natural number n, there is a
prime number greater than n. Goldbach's weak conjecture states
that every odd number greater than 5 is the sum of three
primes. Look up the definition of a Fermat prime or any of the
other statements, if necessary.
In this chapter, we describe an alternative approach to constructing
proofs, using tactics. A proof term is a representation of a
mathematical proof; tactics are commands, or instructions, that
describe how to build such a proof. Informally, you might begin a
mathematical proof by saying “to prove the forward direction, unfold
the definition, apply the previous lemma, and simplify.” Just as these
are instructions that tell the reader how to find the relevant proof,
tactics are instructions that tell Lean how to construct a proof
term. They naturally support an incremental style of writing proofs,
in which you decompose a proof and work on goals one step at a time.
We will describe proofs that consist of sequences of tactics as
“tactic-style” proofs, to contrast with the ways of writing proof
terms we have seen so far, which we will call “term-style”
proofs. Each style has its own advantages and disadvantages. For
example, tactic-style proofs can be harder to read, because they
require the reader to predict or guess the results of each
instruction. But they can also be shorter and easier to
write. Moreover, tactics offer a gateway to using Lean's automation,
since automated procedures are themselves tactics.
Conceptually, stating a theorem or introducing a have statement
creates a goal, namely, the goal of constructing a term with the
expected type. For example, the following creates the goal of
constructing a term of type p∧q∧p, in a context with constants
pq:Prop, hp:p and hq:q:
Indeed, if you replace the “sorry” by an underscore in the example
above, Lean will report that it is exactly this goal that has been
left unsolved.
Ordinarily, you meet such a goal by writing an explicit term. But
wherever a term is expected, Lean allows us to insert instead a
by <tactics> block, where <tactics> is a sequence of commands,
separated by semicolons or line breaks. You can prove the theorem above
in that way:
The apply tactic applies an expression, viewed as denoting a
function with zero or more arguments. It unifies the conclusion with
the expression in the current goal, and creates new goals for the
remaining arguments, provided that no later arguments depend on
them. In the example above, the command applyAnd.intro yields two
subgoals:
The first goal is met with the command exacthp. The exact
command is just a variant of apply which signals that the
expression given should fill the goal exactly. It is good form to use
it in a tactic proof, since its failure signals that something has
gone wrong. It is also more robust than apply, since the
elaborator takes the expected type, given by the target of the goal,
into account when processing the expression that is being applied. In
this case, however, apply would work just as well.
You can see the resulting proof term with the #print command:
You can write a tactic script incrementally. In VS Code, you can open
a window to display messages by pressing CtrlShiftEnter, and
that window will then show you the current goal whenever the cursor is
in a tactic block. If the proof is incomplete, the token by is
decorated with a red squiggly line, and the error message contains the
remaining goals.
Tactic commands can take compound expressions, not just single
identifiers. The following is a shorter version of the preceding
proof:
Tactics that may produce multiple subgoals often tag them. For
example, the tactic applyAnd.intro tagged the first subgoal as
leftleftp:Propq:Prophp:phq:q⊢ p, and the second as rightrightp:Propq:Prophp:phq:q⊢ q∧p. In the case of the apply
tactic, the tags are inferred from the parameters' names used in the
And.intro declaration. You can structure your tactics using the
notation case <tag> => <tactics>. The following is a structured
version of our first tactic proof in this chapter.
Note that Lean hides the other goals inside the case block. After caseleft=>,
the proof state is:
p:Propq:Prophp:phq:q⊢ q
We say that case is “focusing” on the selected goal. Moreover, Lean flags an error
if the selected goal is not fully solved at the end of the case
block.
For simple subgoals, it may not be worth selecting a subgoal using its
tag, but you may still want to structure the proof. Lean also provides
the “bullet” notation . <tactics> (or · <tactics>) for
structuring proofs:
In addition to apply and exact, another useful tactic is
intro, which introduces a hypothesis. What follows is an example
of an identity from propositional logic that we proved in a previous
chapter, now proved using tactics.
As the apply tactic is a command for constructing function
applications interactively, the intro tactic is a command for
constructing function abstractions interactively (i.e., terms of the
form funx=>e). As with lambda abstraction notation, the
intro tactic allows us to use an implicit match.
The intros tactic can be used without any arguments, in which
case, it chooses names and introduces as many variables as it can. You
will see an example of this in a moment.
The assumption tactic looks through the assumptions in context of
the current goal, and if there is one matching the conclusion, it
applies it.
Note that names automatically generated by Lean are inaccessible by default. The motivation is to
ensure your tactic proofs do not rely on automatically generated names, and are consequently more robust.
However, you can use the combinator unhygienic to disable this restriction.
You can also use the rename_i tactic to rename the most recent inaccessible names in your context.
In the following example, the tactic rename_ih1_h2 renames two of the last three hypotheses in
your context.
The rfl tactic solves goals that are reflexive relations applied to definitionally equal arguments.
Equality is reflexive:
example(y:Nat):(funVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x:Nat=>0)y=0:=byy:Nat⊢ (funx=>0)y=0rflAll goals completed! 🐙
The repeat combinator can be used to apply a tactic several times:
But revert is even more clever, in that it will revert not only an
element of the context but also all the subsequent elements of the
context that depend on it. For example, reverting x in the example
above brings h along with it:
You can only revert an element of the local context, that is, a
local variable or hypothesis. But you can replace an arbitrary
expression in the goal by a fresh variable using the generalize
tactic:
The mnemonic in the notation above is that you are generalizing the
goal by setting 3 to an arbitrary variable x. Be careful: not
every generalization preserves the validity of the goal. Here,
generalize replaces a goal that could be proved using
rfl with one that is not provable:
In this example, the sorry tactic is the analogue of the sorry
proof term. It closes the current goal, producing the usual warning
that sorry has been used. To preserve the validity of the previous
goal, the generalize tactic allows us to record the fact that
3 has been replaced by x. All you need to do is to provide a
label, and generalize uses it to store the assignment in the local
context:
Some additional tactics are useful for constructing and destructing
propositions and data. For example, when applied to a goal of the form
p∨q, you use tactics such as applyOr.inl and
applyOr.inr. Conversely, the cases tactic can be used to decompose a
disjunction:
You will see in Inductive Types that
these tactics are quite general. The cases tactic can be used to
decompose any element of an inductively defined type; constructor
always applies the first applicable constructor of an inductively defined type.
For example, you can use cases and constructor with an existential quantifier:
Here, the constructor tactic leaves the first component of the
existential assertion, the value of x, implicit. It is represented
by a metavariable, which should be instantiated later on. In the
previous example, the proper value of the metavariable is determined
by the tactic exactpx, since px has type px. If you want
to specify a witness to the existential quantifier explicitly, you can
use the exists tactic instead:
These tactics can be used on data just as well as propositions. In the
next example, they are used to define functions which swap the
components of the product and sum types:
Note that up to the names we have chosen for the variables, the
definitions are identical to the proofs of the analogous propositions
for conjunction and disjunction. The cases tactic will also do a
case distinction on a natural number:
Tactics often provide an efficient way of building a proof, but long
sequences of instructions can obscure the structure of the
argument. In this section, we describe some means that help provide
structure to a tactic-style proof, making such proofs more readable
and robust.
One thing that is nice about Lean's proof-writing syntax is that it is
possible to mix term-style and tactic-style proofs, and pass between
the two freely. For example, the tactics apply and exact
expect arbitrary terms, which you can write using have, show,
and so on. Conversely, when writing an arbitrary Lean term, you can
always invoke the tactic mode by inserting a by
block. The following is a somewhat toy example:
In fact, there is a show tactic, which is similar to the
show expression in a proof term. It simply declares the type of the
goal that is about to be solved, while remaining in tactic
mode.
The types in a have tactic can be omitted, so you can write
have hp := h.left and have hqr := h.right. In fact, with this
notation, you can even omit both the type and the label, in which case
the new fact is introduced with the label this:
Lean also has a let tactic, which is similar to the have
tactic, but is used to introduce local definitions instead of
auxiliary facts. It is the tactic analogue of a let in a proof
term:
As with have, you can leave the type implicit by writing
let a := 3 * 2. The difference between let and have is that
let introduces a local definition in the context, so that the
definition of the local declaration can be unfolded in the proof.
We have used . to create nested tactic blocks. In a nested block,
Lean focuses on the first goal, and generates an error if it has not
been fully solved at the end of the block. This can be helpful in
indicating the separate proofs of multiple subgoals introduced by a
tactic. The notation . is whitespace sensitive and relies on the indentation
to detect whether the tactic block ends. Alternatively, you can
define tactic blocks using curly braces and semicolons:
It is useful to use indentation to structure proof: every time a tactic
leaves more than one subgoal, we separate the remaining subgoals by
enclosing them in blocks and indenting. Thus if the application of
theorem foo to a single goal produces four subgoals, one would
expect the proof to look like this:
apply foo
. <proof of first goal>
. <proof of second goal>
. <proof of third goal>
. <proof of final goal>
or
apply foo
case <tag of first goal> => <proof of first goal>
case <tag of second goal> => <proof of second goal>
case <tag of third goal> => <proof of third goal>
case <tag of final goal> => <proof of final goal>
or
apply foo
{ <proof of first goal> }
{ <proof of second goal> }
{ <proof of third goal> }
{ <proof of final goal> }
In t₁ <;> t₂, the <;> operator provides a parallel version of the sequencing operation:
t₁ is applied to the current goal, and then t₂ is applied to all the resulting subgoals:
This is especially useful when the resulting goals can be finished off
in a uniform way, or, at least, when it is possible to make progress
on all of them uniformly.
The first | t₁ | t₂ | ... | tₙ applies each tᵢ until one succeeds, or else fails:
In the first example, the left branch succeeds, whereas in the second one, it is the right one that succeeds.
In the next three examples, the same compound tactic succeeds in each case:
The tactic tries to solve the left disjunct immediately by assumption;
if that fails, it tries to focus on the right disjunct; and if that
doesn't work, it invokes the assumption tactic.
You will have no doubt noticed by now that tactics can fail. Indeed,
it is the “failure” state that causes the first combinator to
backtrack and try the next tactic. The try combinator builds a
tactic that always succeeds, though possibly in a trivial way:
try t executes t and reports success, even if t fails. It is
equivalent to first| t |skip, where skip is a tactic that does
nothing (and succeeds in doing so). In the next example, the second
constructor succeeds on the right conjunct q∧r (remember that
disjunction and conjunction associate to the right) but fails on the
first. The try tactic ensures that the sequential composition
succeeds:
Be careful: repeat (try t) will loop forever, because the inner tactic never fails.
In a proof, there are often multiple goals outstanding. Parallel
sequencing is one way to arrange it so that a single tactic is applied
to multiple goals, but there are other ways to do this. For example,
all_goals t applies t to all open goals:
In this case, the any_goals tactic provides a more robust solution.
It is similar to all_goals, except it succeeds if its argument
succeeds on at least one goal:
The combinator focus t ensures that t only effects the current
goal, temporarily hiding the others from the scope. So, if t
ordinarily only effects the current goal, focus (all_goals t) has
the same effect as t.
The rw tactic and the simp tactic
were introduced briefly in Calculational Proofs. In this
section and the next, we discuss them in greater detail.
The rw tactic provides a basic mechanism for applying
substitutions to goals and hypotheses, providing a convenient and
efficient way of working with equality. The most basic form of the
tactic is rw [t], where t is a term whose type asserts an
equality. For example, t can be a hypothesis h : x=y in the
context; it can be a general lemma, like
add_comm:∀xy,x+y=y+x, in which the rewrite tactic tries to find suitable
instantiations of x and y; or it can be any compound term
asserting a concrete or general equation. In the following example, we
use this basic form to rewrite the goal using a hypothesis.
In the example above, the first use of rw replaces k with
0 in the goal fk=0. Then, the second one replaces f0
with 0. The tactic automatically closes any goal of the form
t=t. Here is an example of rewriting using a compound expression:
Multiple rewrites can be combined using the notation rw [t_1, ..., t_n],
which is just shorthand for rw[t_1]; ...;rw [t_n]. The previous example can be written as follows:
By default, rw uses an equation in the forward direction, matching
the left-hand side with an expression, and replacing it with the
right-hand side. The notation ←t can be used to instruct the
tactic to use the equality t in the reverse direction.
In this example, the term ←h₁ instructs the rewriter to replace
b with a. In the editors, you can type the backwards arrow as
\l. You can also use the ASCII equivalent, <-.
Sometimes the left-hand side of an identity can match more than one
subterm in the pattern, in which case the rw tactic chooses the
first match it finds when traversing the term. If that is not the one
you want, you can use additional arguments to specify the appropriate
subterm.
In the first example above, the first step rewrites a+b+c to
a + (b+c). The next step applies commutativity to the term
b+c; without specifying the argument, the tactic would instead rewrite
a + (b+c) to (b+c) + a. Finally, the last step applies
associativity in the reverse direction, rewriting a + (c + b) to
a+c+b. The next two examples instead apply associativity to
move the parenthesis to the right on both sides, and then switch b
and c. Notice that the last example specifies that the rewrite
should take place on the right-hand side by specifying the second
argument to Nat.add_comm.
By default, the rw tactic affects only the goal. The notation
rw [t] at h applies the rewrite
Whereas rw is designed as a surgical tool for manipulating a
goal, the simplifier offers a more powerful form of automation. A
number of identities in Lean's library have been tagged with the
[simp] attribute, and the simp tactic uses them to iteratively
rewrite subterms in an expression.
In the first example, the left-hand side of the equality in the goal
is simplified using the usual identities involving 0 and 1, reducing
the goal to x*y = x*y. At that point, simp applies
reflexivity to finish it off. In the second example, simp reduces
the goal to p(x*y), at which point the assumption h
finishes it off. Here are some more examples
with lists:
For operations that are commutative and associative, like
multiplication on the natural numbers, the simplifier uses these two
facts to rewrite an expression, as well as left commutativity. In
the case of multiplication the latter is expressed as follows:
x*(y*z)=y*(x*z). The local modifier tells the simplifier
to use these rules in the current file (or section or namespace, as
the case may be). It may seem that commutativity and
left-commutativity are problematic, in that repeated application of
either causes looping. But the simplifier detects identities that
permute their arguments, and uses a technique known as ordered
rewriting. This means that the system maintains an internal ordering
of terms, and only applies the identity if doing so decreases the
order. With the three identities mentioned above, this has the effect
that all the parentheses in an expression are associated to the right,
and the expressions are ordered in a canonical (though somewhat
arbitrary) way. Two expressions that are equivalent up to
associativity and commutativity are then rewritten to the same
canonical form.
example(wxyz:Nat)(Variable name `p` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_pNote: This linter can be disabled with `set_option linter.unusedVariables false`p:Nat→Prop):x*y+z*w*x=x*w*z+y*x:=byw:Natx:Naty:Natz:Natp:Nat→Prop⊢ x*y+z*w*x=x*w*z+y*xsimpAll goals completed! 🐙example(wxyz:Nat)(p:Nat→Prop)(h:p(x*y+z*w*x)):p(x*w*z+y*x):=byw:Natx:Naty:Natz:Natp:Nat→Proph:p(x*y+z*w*x)⊢ p(x*w*z+y*x)simpw:Natx:Naty:Natz:Natp:Nat→Proph:p(x*y+z*w*x)⊢ p(x*y+w*(x*z));simpathw:Natx:Naty:Natz:Natp:Nat→Proph:p(x*y+w*(x*z))⊢ p(x*y+w*(x*z));assumptionAll goals completed! 🐙
As with rw, you can send simp a list of facts to use,
including general lemmas, local hypotheses, definitions to unfold, and
compound expressions. The simp tactic also recognizes the ←t
syntax that rewrite does. In any case, the additional rules are
added to the collection of identities that are used to simplify a
term.
The simplifier will also do propositional rewriting. For example,
using the hypothesis p, it rewrites p∧q to q and p∨q to True,
which it then proves trivially. Iterating such
rewrites produces nontrivial propositional reasoning.
One thing that makes the simplifier especially useful is that its
capabilities can grow as a library develops. For example, suppose we
define a list operation that symmetrizes its input by appending its
reversal:
But using reverse_mk_symm is generally the right thing to do, and
it would be nice if users did not have to invoke it explicitly. You can
achieve that by marking it as a simplification rule when the theorem
is defined:
Once the attribute is applied, however, there is no way to permanently
remove it; it persists in any file that imports the one where the
attribute is assigned. As we will discuss further in
Attributes, one can limit the scope of an attribute to the
current file or section using the local modifier:
Outside the section, the simplifier will no longer use
reverse_mk_symm by default.
Note that the various simp options we have discussed—giving an
explicit list of rules, and using at to specify the location—can be combined,
but the order they are listed is rigid. You can see the correct order
in an editor by placing the cursor on the simp identifier to see
the documentation string that is associated with it.
There are two additional modifiers that are useful. By default,
simp includes all theorems that have been marked with the
attribute [simp]. Writing simponly excludes these defaults,
allowing you to use a more explicitly crafted list of
rules. In the examples below, the minus sign and
only are used to block the application of reverse_mk_symm.
With +contextual, the simp tactic uses the fact that x=0 when simplifying y+x=y, and
x≠0 when simplifying the other branch. Here is another example:
example:∀(x:Nat)(Variable name `h` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_hNote: This linter can be disabled with `set_option linter.unusedVariables false`h:x=0),y+x=y:=byy:Nat⊢ ∀(x:Nat),x=0→y+x=ysimp+contextualAll goals completed! 🐙
Another useful configuration option is +arith which enables arithmetical simplifications.
The split tactic is useful for breaking nested if-then-else and match expressions in cases.
For a match expression with n cases, the split tactic generates at most n subgoals. Here is an example:
In the following example, we define the notation triv using the command syntax.
Then, we use the command macro_rules to specify what should
be done when triv is used. You can provide different expansions, and the tactic
interpreter will try all of them until one succeeds:
-- Define a new tactic notationsyntax"triv":tacticmacro_rules|`(tactic|triv)=>`(tactic|assumption)example(h:p):p:=byp:Sort ?u.2h:p⊢ ptrivAll goals completed! 🐙-- You cannot prove the following theorem using `triv`-- example (x : α) : x = x := by-- triv-- Let's extend `triv`. The tactic interpreter-- tries all possible macro extensions for `triv` until one succeedsmacro_rules|`(tactic|triv)=>`(tactic|rfl)example(x:α):x=x:=byα:Sort u_1x:α⊢ x=xtrivAll goals completed! 🐙example(x:α)(h:p):x=x∧p:=byα:Sort u_1p:Propx:αh:p⊢ x=x∧papplyAnd.introleftα:Sort u_1p:Propx:αh:p⊢ x=xrightα:Sort u_1p:Propx:αh:p⊢ p<;>leftα:Sort u_1p:Propx:αh:p⊢ x=xrightα:Sort u_1p:Propx:αh:p⊢ ptrivAll goals completed! 🐙-- We now add a (recursive) extensionmacro_rules|`(tactic|triv)=>`(tactic|applyAnd.intro<;>triv)example(x:α)(h:p):x=x∧p:=byα:Sort u_1p:Propx:αh:p⊢ x=x∧ptrivAll goals completed! 🐙
You are now familiar with the fundamentals of dependent type theory,
both as a language for defining mathematical objects and a language
for constructing proofs. The one thing you are missing is a mechanism
for defining new data types. We will fill this gap in the next
chapter, which introduces the notion of an inductive data type. But
first, in this chapter, we take a break from the mechanics of type
theory to explore some pragmatic aspects of interacting with Lean.
Not all of the information found here will be useful to you right
away. We recommend skimming this section to get a sense of Lean's
features, and then returning to it as necessary.
Errors are produced when an inconsistency in the code means that it can't
be processed. Examples include syntax errors (e.g. a missing )) and type
errors such as attempting to add a natural number to a function.
Warnings
Warnings describe potential problems with the code, such as the presence of sorry.
Unlike with errors, the code is not meaningless; however, warnings deserve careful attention.
Information
Information doesn't indicate any problem with the code, and includes output from commands such as #check and #eval.
Lean can check that a command produces the expected messages. If the messages match,
then any errors are disregarded; this can be used to ensure that the right errors occur.
If they don't, an error is produced. You can use the #guard_msgs command to indicate
which messages are expected.
Here is an example:
/--
error: Type mismatch
"Not a number"
has type
String
but is expected to have type
Nat
-/#guard_msgsindefx:Nat:="Not a number"
Including a message category in parentheses after #guard_msgs causes it to check only
the specified category, letting others through. In this example, #eval issues an error
due to the presence of sorry, but the warning that is always issued for sorry is displayed
as usual:
/--
error: Aborting evaluation since the expression depends on the
'sorry' axiom, which can lead to runtime instability and crashes.
To attempt to evaluate anyway despite the risks, use the '#eval!'
command.
-/#guard_msgs(error)indeclaration uses `sorry`#eval(sorry:Nat)
declaration uses `sorry`
Without the configuration, both messages are captured:
/--
error: Aborting evaluation since the expression depends on the 'sorry'
axiom, which can lead to runtime instability and crashes.
To attempt to evaluate anyway despite the risks, use the '#eval!'
command.
---
warning: declaration uses `sorry`
-/#guard_msgsin#eval(sorry:Nat)
Some examples in this book use #guard_msgs to indicate expected errors.
The goal of Lean's front end is to interpret user input, construct
formal expressions, and check that they are well-formed and type-correct.
Lean also supports the use of various editors, which provide
continuous checking and feedback. More information can be found on the
Lean documentation pages.
The definitions and theorems in Lean's standard library are spread
across multiple files. Users may also wish to make use of additional
libraries, or develop their own projects across multiple files. When
Lean starts, it automatically imports the contents of the library
Init folder, which includes a number of fundamental definitions
and constructions. As a result, most of the examples we present here
work “out of the box.”
If you want to use additional files, however, they need to be imported
manually, via an import statement at the beginning of a file. The
command
import Bar.Baz.Blah
imports the file Bar/Baz/Blah.olean, where the descriptions are
interpreted relative to the Lean search path. Information as to how
the search path is determined can be found on the
documentation pages.
By default, it includes the standard library directory, and (in some contexts)
the root of the user's local project.
Importing is transitive. In other words, if you import Foo and Foo imports Bar,
then you also have access to the contents of Bar, and do not need to import it explicitly.
Lean provides various sectioning mechanisms to help structure a
theory. You saw in Variables and Sections that the
section command makes it possible not only to group together
elements of a theory that go together, but also to declare variables
that are inserted as arguments to theorems and definitions, as
necessary. Remember that the point of the variable command is to
declare variables for use in theorems, as in the following example:
The definition of double does not have to declare x as an
argument; Lean detects the dependence and inserts it
automatically. Similarly, Lean detects the occurrence of x in
t1 and t2, and inserts it automatically there, too.
Note that double does not have y as argument. Variables are only
included in declarations where they are actually used.
In Lean, identifiers are given by hierarchical names like
Foo.Bar.baz. We saw in Namespaces that Lean provides
mechanisms for working with hierarchical names. The command
namespace Foo causes Foo to be prepended to the name of each
definition and theorem until end Foo is encountered. The command
open Foo then creates temporary aliases to definitions and
theorems that begin with prefix Foo.
Although the names of theorems and definitions have to be unique, the
aliases that identify them do not. When we open a namespace, an
identifier may be ambiguous. Lean tries to use type information to
disambiguate the meaning in context, but you can always disambiguate
by giving the full name. To that end, the string _root_ is an
explicit description of the empty prefix.
creates aliases for succ, add, and sub in the current
namespace, so that whenever the namespace is open, these aliases are
available. If this command is used outside a namespace, the aliases
are exported to the top level.
The main function of Lean is to translate user input to formal
expressions that are checked by the kernel for correctness and then
stored in the environment for later use. But some commands have other
effects on the environment, either assigning attributes to objects in
the environment, defining notation, or declaring instances of type
classes, as described in the chapter on type classes. Most of
these commands have global effects, which is to say, they remain
in effect not only in the current file, but also in any file that
imports it. However, such commands often support the local modifier,
which indicates that they only have effect until
the current section or namespace is closed, or until the end
of the current file.
In Using the Simplifier,
we saw that theorems can be annotated with the [simp] attribute,
which makes them available for use by the simplifier.
The following example defines the prefix relation on lists,
proves that this relation is reflexive, and assigns the [simp] attribute to that theorem.
In all these cases, the attribute remains in effect in any file that
imports the one in which the declaration occurs. Adding the local
modifier restricts the scope:
sectiontheoremList.isPrefix_self(as:Listα):isPrefixasas:=⟨[],byα:Type u_1as:Listα⊢ as++[]=assimpAll goals completed! 🐙⟩attribute[localsimp]List.isPrefix_selfexample:isPrefix[1,2,3][1,2,3]:=by⊢ isPrefix[1,2,3][1,2,3]simpAll goals completed! 🐙end/-- error: `simp` made no progress -/#guard_msgsinexample:isPrefix[1,2,3][1,2,3]:=by⊢ isPrefix[1,2,3][1,2,3]simp⊢ isPrefix[1,2,3][1,2,3]
For another example, we can use the instance command to assign the
notation ≤ to the isPrefix relation. That command, which will
be explained in the chapter on type classes, works by
assigning an [instance] attribute to the associated definition.
abbrevinstLe:LE(Listα):={le:=isPrefix}sectionattribute[localinstance]instLeexample(as:Listα):as≤as:=⟨[],byα:Type u_1as:Listα⊢ as++[]=assimpAll goals completed! 🐙⟩end/--
error: failed to synthesize instance of type class
LE (List α)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
-/#guard_msgsinexample(as:Listα):as≤as:=⟨[],bysimp⟩
In Notation below, we will discuss Lean's
mechanisms for defining notation, and see that they also support the
local modifier. However, in Setting Options, we will
discuss Lean's mechanisms for setting options, which does not follow
this pattern: options can only be set locally, which is to say,
their scope is always restricted to the current section or current
file.
In Implicit Arguments,
we saw that if Lean displays the type
of a term t as {x:α}→βx, then the curly brackets
indicate that x has been marked as an implicit argument to
t. This means that whenever you write t, a placeholder, or
“hole,” is inserted, so that t is replaced by @t_. If you
don't want that to happen, you have to write @t instead.
Notice that implicit arguments are inserted eagerly. Suppose we define
a function f : (x:Nat)→{y:Nat}→(z:Nat)→Nat.
Then, when we write the expression f7 without further
arguments, it is parsed as @f7_.
Lean offers a weaker annotation which specifies that a placeholder should only be added
before a subsequent explicit argument. It can be written with double braces, so the type of f would be
f : (x:Nat)→{{y:Nat}}→(z:Nat)→Nat.
With this annotation, the expression f7 would be parsed as is, whereas f73 would be
parsed as @f7_3, just as it would be with the strong annotation.
This annotation can also be written as ⦃y : Nat⦄, where the Unicode brackets are entered
as \{{ and \}}, respectively.
To illustrate the difference, consider the following example, which
shows that a reflexive euclidean relation is both symmetric and
transitive.
The results are broken down into small steps: th1 shows that a
relation that is reflexive and euclidean is symmetric, and th2
shows that a relation that is symmetric and euclidean is
transitive. Then th3 combines the two results. But notice that we
have to manually disable the implicit arguments in euclr, because
otherwise too many implicit arguments are inserted. The problem goes
away if we use weak implicit arguments:
There is a third kind of implicit argument that is denoted with square
brackets, [ and ]. These are used for type classes, as
explained in the chapter on type classes.
Identifiers in Lean can include any alphanumeric characters, including
Greek characters (other than ∀ , Σ , and λ , which, as we have seen,
have a special meaning in the dependent type theory). They can also
include subscripts, which can be entered by typing \_ followed by
the desired subscripted character.
Lean's parser is extensible, which is to say, we can define new notation.
Lean's syntax can be extended and customized by users at every level,
ranging from basic “mixfix” notations to custom elaborators. In fact,
all builtin syntax is parsed and processed using the same mechanisms
and APIs open to users. In this section, we will describe and explain
the various extension points.
While introducing new notations is a relatively rare feature in
programming languages and sometimes even frowned upon because of its
potential to obscure code, it is an invaluable tool in formalization
for expressing established conventions and notations of the respective
field succinctly in code. Going beyond basic notations, Lean's
ability to factor out common boilerplate code into (well-behaved)
macros and to embed entire custom domain specific languages (DSLs) to
textually encode subproblems efficiently and readably can be of great
benefit to both programmers and proof engineers alike.
After the initial command name describing the operator kind (its
“fixity”), we give the parsing precedence of the operator preceded
by a colon :, then a new or existing token surrounded by double
quotes (the whitespace is used for pretty printing), then the function
this operator should be translated to after the arrow =>.
The precedence is a natural number describing how “tightly” an
operator binds to its arguments, encoding the order of operations. We
can make this more precise by looking at the commands the above unfold to:
It turns out that all commands from the first code block are in fact
command macros translating to the more general notation command.
We will learn about writing such macros below. Instead of a single
token, the notation command accepts a mixed sequence of tokens and
named term placeholders with precedences, which can be referenced on
the right-hand side of => and will be replaced by the respective
term parsed at that position. A placeholder with precedence p
accepts only notations with precedence at least p in that place.
Thus the string a+b+c cannot be parsed as the equivalent of
a+(b+c) because the right-hand side operand of an infixl notation
has precedence one greater than the notation itself. In contrast,
infixr reuses the notation's precedence for the right-hand side
operand, so a^b^ccan be parsed as a^(b^c). Note that
if we used notation directly to introduce an infix notation like
where the precedences do not sufficiently determine associativity,
Lean's parser will default to right associativity. More precisely,
Lean's parser follows a local longest parse rule in the presence of
ambiguous grammars: when parsing the right-hand side of a ~ in
a~b~c, it will continue parsing as long as possible (as the current
precedence allows), not stopping after b but parsing ~c as well.
Thus the term is equivalent to a~(b~c).
As mentioned above, the notation command allows us to define
arbitrary mixfix syntax freely mixing tokens and placeholders.
Placeholders without precedence default to 0, i.e. they accept notations of any precedence in their place.
If two notations overlap, we again apply the longest parse rule:
The new notation is preferred to the binary notation since the latter,
before chaining, would stop parsing after 1+2. If there are
multiple notations accepting the same longest parse, the choice will
be delayed until elaboration, which will fail unless exactly one
overload is type-correct.
In Lean, the type of natural numbers, Nat, is different from the
type of integers, Int. But there is a function Int.ofNat that
embeds the natural numbers in the integers, meaning that we can view
any natural number as an integer, when needed. Lean has mechanisms to
detect and insert coercions of this sort. Coercions can be explicitly
requested using the overloaded ↑ operator.
There are a number of ways in which you can query Lean for information
about its current state and the objects and theorems that are
available in the current context. You have already seen two of the
most common ones, #check and #eval. Remember that #check
is often used in conjunction with the @ operator, which makes all
of the arguments to a theorem or definition explicit. In addition, you
can use the #print command to get information about any
identifier. If the identifier denotes a definition or theorem, Lean
prints the type of the symbol, and its definition. If it is a constant
or an axiom, Lean indicates that fact, and shows the type.
The command set_optionpp.alltrue carries out these settings all
at once, whereas set_optionpp.allfalse reverts to the previous
values. Pretty printing additional information is often very useful
when you are debugging a proof, or trying to understand a cryptic
error message. Too much information can be overwhelming, though, and
Lean's defaults are generally sufficient for ordinary interactions.
To use Lean effectively you will inevitably need to make use of
definitions and theorems in the library. Recall that the import
command at the beginning of a file imports previously compiled results
from other files, and that importing is transitive; if you import
Foo and Foo imports Bar, then the definitions and theorems
from Bar are available to you as well. But the act of opening a
namespace, which provides shorter names, does not carry over. In each
file, you need to open the namespaces you wish to use.
In general, it is important for you to be familiar with the library
and its contents, so you know what theorems, definitions, notations,
and resources are available to you. Below we will see that Lean's
editor modes can also help you find things you need, but studying the
contents of the library directly is often unavoidable. Lean's standard
library can be found online, on GitHub:
You can see the contents of these directories and files using GitHub's
browser interface. If you have installed Lean on your own computer,
you can find the library in the lean folder, and explore it with
your file manager. Comment headers at the top of each file provide
additional information.
Lean's library developers follow general naming guidelines to make it
easier to guess the name of a theorem you need, or to find it using
tab completion in editors with a Lean mode that supports this, which
is discussed in the next section. Identifiers are generally
camelCase, and types are CamelCase. For theorem names,
we rely on descriptive names where the different components are separated
by _s. Often the name of theorem simply describes the conclusion:
Remember that identifiers in Lean can be organized into hierarchical
namespaces. For example, the theorem named le_of_succ_le_succ in the
namespace Nat has full name Nat.le_of_succ_le_succ, but the shorter
name is made available by the command open Nat (for names not marked as
protected). We will see in the chapters on inductive types
and structures and records
that defining structures and inductive data types in Lean generates
associated operations, and these are stored in
a namespace with the same name as the type under definition. For
example, the product type comes with the following operations:
The first is used to construct a pair, whereas the next two,
Prod.fst and Prod.snd, project the two elements. The last,
Prod.rec, provides another mechanism for defining functions on a
product in terms of a function on the two components. Names like
Prod.rec are protected, which means that one has to use the full
name even when the Prod namespace is open.
With the propositions as types correspondence, logical connectives are
also instances of inductive types, and so we tend to use dot notation
for them as well:
In the previous section, we have shown how implicit arguments make functions more convenient to use.
However, functions such as compose are still quite verbose to define. Note that the universe
polymorphic compose is even more verbose than the one previously defined.
Lean 4 supports a new feature called auto bound implicit arguments. It makes functions such as
compose much more convenient to write. When Lean processes the header of a declaration,
any unbound identifier is automatically added as an implicit argument. With this feature we can write compose as
Note that Lean inferred a more general type using Sort instead of Type.
Although we love this feature and use it extensively when implementing Lean,
we realize some users may feel uncomfortable with it. Thus, you can disable it using
the command set_optionautoImplicitfalse.
set_optionautoImplicitfalse/--
error: Unknown identifier `β`
Note: It is not possible to treat `β` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
---
error: Unknown identifier `γ`
Note: It is not possible to treat `γ` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
---
error: Unknown identifier `α`
Note: It is not possible to treat `α` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
---
error: Unknown identifier `β`
Note: It is not possible to treat `β` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
---
error: Unknown identifier `α`
Note: It is not possible to treat `α` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
---
error: Unknown identifier `γ`
Note: It is not possible to treat `γ` as an implicitly bound variable here because the `autoImplicit` option is set to `false`.
-/#guard_msgsindefcompose(g:β→γ)(f:α→β)(x:α):γ:=g(fx)
When the expected type of an expression is a function that is awaiting implicit
arguments, the elaborator automatically introduces the corresponding lambdas.
For example, pure's type states that the first argument is an implicit type
α, but ReaderT.pure's first argument is the reader monad's context type ρ.
It is automatically surrounded with a fun {α} => ..., which allows the elaborator to
correctly fill in the implicit arguments in the body.
defid1:{α:Type}→α→α:=funx=>xdeflistId:List({α:Type}→α→α):=(funx=>x)::[]-- In this example, implicit lambda introduction has been disabled because-- we use `@` before {kw}`fun`defid2:{α:Type}→α→α:=@funα(x:α)=>id1xdefid3:{α:Type}→α→α:=@funαx=>id1xdefid4:{α:Type}→α→α:=funx=>id1x-- In this example, implicit lambda introduction has been disabled-- because we used the binder annotation `{...}`defid5:{α:Type}→α→α:=fun{α}x=>id1x
Lean includes a notation for describing simple functions using anonymous
placeholders rather than fun. When · occurs as part of a term,
the nearest enclosing parentheses become a function with the · as its argument.
If the parentheses include multiple placeholders without other intervening parentheses,
then they are made into arguments from left to right. Here are a few examples:
Named arguments enable you to specify an argument for a parameter by
matching the argument with its name rather than with its position in
the parameter list. If you don't remember the order of the parameters
but know their names, you can send the arguments in any order. You may
also provide the value for an implicit parameter when Lean failed to
infer it. Named arguments also improve the readability of your code by
identifying what each argument represents.
In the following examples, we illustrate the interaction between named
and default arguments.
deff(x:Nat)(y:Nat:=1)(w:Nat:=2)(z:Nat):=x+y+w-zexample(xz:Nat):f(z:=z)x=x+1+2-z:=rflexample(xz:Nat):fx(z:=z)=x+1+2-z:=rflexample(xy:Nat):fxy=funz=>x+y+2-z:=rflexample:f=(funxz=>x+1+2-z):=rflexample(x:Nat):fx=funz=>x+1+2-z:=rflexample(Variable name `y` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_yNote: This linter can be disabled with `set_option linter.unusedVariables false`y:Nat):f(y:=5)=funxz=>x+5+2-z:=rfldefg{α}[Addα](a:α)(b?:Optionα:=none)(c:α):α:=matchb?with|none=>a+c|someb=>a+b+cvariable{α}[Addα]example:g=fun(ac:α)=>a+c:=rflexample(x:α):g(c:=x)=fun(a:α)=>a+x:=rflexample(x:α):g(b?:=somex)=fun(ac:α)=>a+x+c:=rflexample(x:α):gx=fun(c:α)=>x+c:=rflexample(xy:α):gxy=fun(c:α)=>x+y+c:=rfl
You can use .. to provide missing explicit arguments as _.
This feature combined with named arguments is useful for writing patterns. Here is an example:
We have seen that Lean's formal foundation includes basic types,
Prop, Type0, Type1, Type2, ..., and allows for the formation of
dependent function types, (x:α)→β. In the examples, we have
also made use of additional types like Bool, Nat, and Int,
and type constructors, like List, and product, ×. In fact, in
Lean's library, every concrete type other than the universes and every
type constructor other than dependent arrows is an instance of a general family of
type constructions known as inductive types. It is remarkable that
it is possible to construct a substantial edifice of mathematics based
on nothing more than the type universes, dependent arrow types, and inductive
types; everything else follows from those.
Intuitively, an inductive type is built up from a specified list of
constructors. In Lean, the syntax for specifying such a type is as
follows:
The intuition is that each constructor specifies a way of building new
objects of Foo, possibly from previously constructed values. The
type Foo consists of nothing more than the objects that are
constructed in this way.
We will see below that the arguments of the constructors can include
objects of type Foo, subject to a certain “positivity” constraint,
which guarantees that elements of Foo are built from the bottom
up. Roughly speaking, each ... can be any arrow type constructed from
Foo and previously defined types, in which Foo appears, if at
all, only as the “target” of the dependent arrow type.
We will provide a number of examples of inductive types. We will also
consider slight generalizations of the scheme above, to mutually
defined inductive types, and so-called inductive families.
As with the logical connectives, every inductive type comes with
introduction rules, which show how to construct an element of the
type, and elimination rules, which show how to “use” an element of the
type in another construction. The analogy to the logical connectives
should not come as a surprise; as we will see below, they, too, are
examples of inductive type constructions. You have already seen the
introduction rules for an inductive type: they are just the
constructors that are specified in the definition of the type. The
elimination rules provide for a principle of recursion on the type,
which includes, as a special case, a principle of induction as well.
In the next chapter, we will describe Lean's function definition
package, which provides even more convenient ways to define functions
on inductive types and carry out inductive proofs. But because the
notion of an inductive type is so fundamental, we feel it is important
to start with a low-level, hands-on understanding. We will start with
some basic examples of inductive types, and work our way up to more
elaborate and complex examples.
Think of sunday, monday, ... , saturday as
being distinct elements of Weekday, with no other distinguishing
properties. The elimination principle, Weekday.rec, is defined
along with the type Weekday and its constructors. It is also known
as a recursor, and it is what makes the type “inductive”: it allows
us to define a function on Weekday by assigning values
corresponding to each constructor. The intuition is that an inductive
type is exhaustively generated by the constructors, and has no
elements beyond those they construct.
When using Lean's logic, the match expression is compiled using the recursorWeekday.rec generated when
you declare the inductive type. This ensures that the resulting term is well-defined in the type theory. For compiled code,
match is compiled as in other functional programming languages.
When declaring an inductive datatype, you can use derivingRepr to instruct
Lean to generate a function that converts Weekday objects into text.
This function is used by the #eval command to display Weekday objects.
If no Repr exists, #eval attempts to derive one on the spot.
It is often useful to group definitions and theorems related to a
structure in a namespace with the same name. For example, we can put
the numberOfDay function in the Weekday namespace. We are
then allowed to use the shorter name when we open the namespace.
Tactics for Inductive Types below will introduce additional
tactics that are specifically designed to make use of inductive types.
Notice that, under the propositions-as-types correspondence, we can
use match to prove theorems as well as define functions. In other
words, under the propositions-as-types correspondence, the proof by
cases is a kind of definition by cases, where what is being “defined”
is a proof instead of a piece of data.
The Bool type in the Lean library is an instance of
enumerated type.
(To run these examples, we put them in a namespace called Hidden,
so that a name like Bool does not conflict with the Bool in
the standard library. This is necessary because these types are part
of the Lean “prelude” that is automatically imported when the system
is started.)
As an exercise, you should think about what the introduction and
elimination rules for these types do. As a further exercise, we
suggest defining boolean operations and, or, not on the
Bool type, and verifying common identities. Note that you can define a
binary operation like and using match:
Enumerated types are a very special case of inductive types, in which
the constructors take no arguments at all. In general, a
“construction” can depend on data, which is then represented in the
constructed argument. Consider the definitions of the product type and
sum type in the library:
Consider what is going on in these examples.
The product type has one constructor, Prod.mk,
which takes two arguments. To define a function on Prodαβ, we
can assume the input is of the form Prod.mkab, and we have to
specify the output, in terms of a and b. We can use this to
define the two projections for Prod. Remember that the standard
library defines notation α×β for Prodαβ and (a,b) for
Prod.mkab.
deffst{α:Typeu}{β:Typev}(p:Prodαβ):α:=matchpwith|Prod.mkaVariable name `b` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_bNote: This linter can be disabled with `set_option linter.unusedVariables false`b=>adefsnd{α:Typeu}{β:Typev}(p:Prodαβ):β:=matchpwith|Prod.mkVariable name `a` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_aNote: This linter can be disabled with `set_option linter.unusedVariables false`ab=>b
endHidden
The function fst takes a pair, p. The match interprets
p as a pair, Prod.mkab. Recall also from Dependent Type Theory
that to give these definitions the greatest generality possible, we allow
the types α and β to belong to any universe.
Here is another example where we use the recursor Prod.casesOn instead
of match.
The argument motive is used to specify the type of the object you want to
construct, and it is a function because it may depend on the pair.
The cond function is a boolean conditional: condbt1t2
returns t1 if b is true, and t2 otherwise.
The function prod_example takes a pair consisting of a boolean,
b, and a number, n, and returns either 2*n or 2*n+1
according to whether b is true or false.
In contrast, the sum type has two constructors, inl and inr
(for “insert left” and “insert right”), each of which takes one
(explicit) argument. To define a function on Sumαβ, we have to
handle two cases: either the input is of the form inla, in which
case we have to specify an output value in terms of a, or the
input is of the form inrb, in which case we have to specify an
output value in terms of b.
This example is similar to the previous one, but now an input to
sum_example is implicitly either of the form inln or inrn.
In the first case, the function returns 2*n, and the second
case, it returns 2*n+1.
Notice that the product type depends on parameters αβ : Type
which are arguments to the constructors as well as Prod. Lean
detects when these arguments can be inferred from later arguments to a
constructor or the return type, and makes them implicit in that case.
In Defining the Natural Numbers
we will see what happens when the
constructor of an inductive type takes arguments from the inductive
type itself. What characterizes the examples we consider in this
section is that each constructor relies only on previously specified types.
Notice that a type with multiple constructors is disjunctive: an
element of Sumαβ is either of the form inlaor of the
form inlb. A constructor with multiple arguments introduces
conjunctive information: from an element Prod.mkab of
Prodαβ we can extract aandb. An arbitrary inductive type can
include both features, by having any number of constructors, each of
which takes any number of arguments.
As with function definitions, Lean's inductive definition syntax will
let you put named arguments to the constructors before the colon:
The results of these definitions are essentially the same as the ones given earlier in this section.
A type, like Prod, that has only one constructor is purely
conjunctive: the constructor simply packs the list of arguments into a
single piece of data, essentially a tuple where the type of subsequent
arguments can depend on the type of the initial argument. We can also
think of such a type as a “record” or a “structure”. In Lean, the
keyword structure can be used to define such an inductive type as
well as its projections, at the same time.
This example simultaneously introduces the inductive type, Prod,
its constructor, mk, the usual eliminators (rec and
recOn), as well as the projections, fst and snd, as
defined above.
If you do not name the constructor, Lean uses mk as a default. For
example, the following defines a record to store a color as a triple
of RGB values:
The definition of yellow forms the record with the three values
shown, and the projection Color.red returns the red component.
The structure command is especially useful for defining algebraic
structures, and Lean provides substantial infrastructure to support
working with them. Here, for example, is the definition of a
semigroup:
In the semantics of dependent type theory, there is no built-in notion
of a partial function. Every element of a function type α→β or a
dependent function type (a:α)→β is assumed to have a value
at every input. The Option type provides a way of representing partial functions. An
element of Optionβ is either none or of the form someb,
for some value b : β. Thus we can think of an element f of the
type α→Optionβ as being a partial function from α to β:
for every a : α, fa either returns none, indicating
fa is “undefined”, or someb.
An element of Inhabitedα is simply a witness to the fact that
there is an element of α. Later, we will see that Inhabited is
an example of a type class in Lean: Lean can be instructed that
suitable base types are inhabited, and can automatically infer that
other constructed types are inhabited on that basis.
As exercises, we encourage you to develop a notion of composition for
partial functions from α to β and β to γ, and show
that it behaves as expected. We also encourage you to show that
Bool and Nat are inhabited, that the product of two inhabited
types is inhabited, and that the type of functions to an inhabited
type is inhabited.
Inductively defined types can live in any type universe, including the
bottom-most one, Prop. In fact, this is exactly how the logical
connectives are defined.
You should think about how these give rise to the introduction and
elimination rules that you have already seen. There are rules that
govern what the eliminator of an inductive type can eliminate to,
that is, what kinds of types can be the target of a recursor. Roughly
speaking, what characterizes inductive types in Prop is that one
can only eliminate to other types in Prop. This is consistent with
the understanding that if p : Prop, an element hp : p carries
no data. There is a small exception to this rule, however, which we
will discuss below, in Inductive Families.
Even the existential quantifier is inductively defined:
Keep in mind that the notation ∃x:α,p is syntactic sugar for Exists(funx:α=>p).
The definitions of False, True, And, and Or are
perfectly analogous to the definitions of Empty, Unit,
Prod, and Sum. The difference is that the first group yields
elements of Prop, and the second yields elements of Typeu for
some u. In a similar way, ∃x:α,p is a Prop-valued
variant of Σx:α,β.
This is a good place to mention another inductive type, denoted
{x:α//p}, which is sort of a hybrid between
∃x:α,p and Σx:α,β.
The notation {x:α//px} is syntactic sugar for Subtype(funx:α=>px).
It is modeled after subset notation in set theory: the idea is that {x:α//px}
denotes the collection of elements of α that have property p.
The inductively defined types we have seen so far are “flat”:
constructors wrap data and insert it into a type, and the
corresponding recursor unpacks the data and acts on it. Things get
much more interesting when the constructors act on elements of the
very type being defined. A canonical example is the type Nat of
natural numbers:
There are two constructors. We start with zero : Nat; it takes
no arguments, so we have it from the start. In contrast, the
constructor succ can only be applied to a previously constructed
Nat. Applying it to zero yields succzero:Nat. Applying
it again yields succ(succzero):Nat, and so on. Intuitively,
Nat is the “smallest” type with these constructors, meaning that
it is exhaustively (and freely) generated by starting with zero
and applying succ repeatedly.
As before, the recursor for Nat is designed to define a dependent
function f from Nat to any domain, that is, an element f
of (n:Nat)→motiven for some motive : Nat→Sortu.
It has to handle two cases: the case where the input is zero, and the case where
the input is of the form succn for some n : Nat. In the first
case, we simply specify a target value with the appropriate type, as
before. In the second case, however, the recursor can assume that a
value of f at n has already been computed. As a result, the
next argument to the recursor specifies a value for f(succn) in
terms of n and fn. If we check the type of the recursor,
you find the following:
The implicit argument, motive, is the codomain of the function being defined.
In type theory it is common to say motive is the motive for the elimination/recursion,
since it describes the kind of object we wish to construct.
The next two arguments specify how to compute the zero and successor cases, as described above.
They are also known as the minor premises.
Finally, the t:Nat is the input to the function. It is also known as the major premise.
The Nat.recOn is similar to Nat.rec but the major premise occurs before the minor premises.
Consider, for example, the addition function addmn on the
natural numbers. Fixing m, we can define addition by recursion on
n. In the base case, we set addmzero to m. In the
successor step, assuming the value addmn is already determined,
we define addm(succn) to be succ(addmn).
inductiveNatwhere|zero:Nat|succ:Nat→NatderivingReprdefadd(mn:Nat):Nat:=matchnwith|Nat.zero=>m|Nat.succn=>Nat.succ(addmn)openAmbiguous namespace `Nat`: it is interpreted as `_root_.Hidden.Nat` because this `open` occurs inside `namespace Hidden`, while `_root_.Nat` is silently not opened. Specify the namespace unambiguously, e.g. `_root_.Hidden.Nat`. The warning can sometimes also be addressed by moving the `open` outside of the surrounding `namespace`.Note: This linter can be disabled with `set_option linter.ambiguousOpen false`NatHidden.Nat.succ (Hidden.Nat.succ (Hidden.Nat.succ (Hidden.Nat.zero)))#evaladd(succ(succzero))(succzero)
It is useful to put such definitions into a namespace, Nat. We can
then go on to define familiar notation in that namespace. The two
defining equations for addition now hold definitionally:
We will explain how the instance command works in
the Type Classes chapter. In the examples below, we will use
Lean's version of the natural numbers.
Proving a fact like 0+n=n, however, requires a proof by induction.
As observed above, the induction principle is just a special case of the recursion principle,
when the codomain motiven is an element of Prop. It represents the familiar
pattern of an inductive proof: to prove ∀n,motiven, first prove motive0,
and then, for arbitrary n, assume ih : motiven and prove motive(n+1).
Notice that, once again, when Nat.recOn is used in the context of
a proof, it is really the induction principle in disguise. The
rw and simp tactics tend to be very effective in proofs
like these. In this case, each can be used to reduce the proof to:
openNattheoremzero_add(n:Nat):0+n=n:=Nat.recOn(motive:=funx=>0+x=x)nrfl(funnih=>byn✝:Natn:Natih:0+n=n⊢ 0+n.succ=n.succsimp[This simp argument is unused:ihHint: Omit it from the simp argument list.[apply]simpNote: This linter can be disabled with `set_option linter.unusedSimpArgs false`ih]All goals completed! 🐙)
endHidden
As another example, let us prove the associativity of addition,
∀mnk,m+n+k=m+(n+k).
(The notation +, as we have defined it, associates to the left, so m+n+k is really (m+n)+k.)
The hardest part is figuring out which variable to do the induction on. Since addition is defined by recursion on the second argument,
k is a good guess, and once we make that choice the proof almost writes itself:
openAmbiguous namespace `Nat`: it is interpreted as `_root_.Hidden.Nat` because this `open` occurs inside `namespace Hidden`, while `_root_.Nat` is silently not opened. Specify the namespace unambiguously, e.g. `_root_.Hidden.Nat`. The warning can sometimes also be addressed by moving the `open` outside of the surrounding `namespace`.Note: This linter can be disabled with `set_option linter.ambiguousOpen false`Nattheoremsucc_add(nm:Nat):succn+m=succ(n+m):=Nat.recOn(motive:=funx=>succn+x=succ(n+x))mrfl(funmih=>byn:Natm✝:Natm:Natih:n.succ+m=(n+m).succ⊢ n.succ+m.succ=(n+m.succ).succsimpa[add_succ(succn)]All goals completed! 🐙)theoremadd_comm(mn:Nat):m+n=n+m:=Nat.recOn(motive:=funx=>m+x=x+m)n(bym:Natn:Nat⊢ m+zero=zero+msimp[add_zero,zero_add]All goals completed! 🐙)(funmih=>bym✝:Natn:Natm:Natih:m✝+m=m+m✝⊢ m✝+m.succ=m.succ+m✝simp_all[succ_add,add_succ]All goals completed! 🐙)
A list of elements of type α is either the empty list, nil, or
an element h:α followed by a list t:Listα.
The first element, h, is commonly known as the “head” of the list,
and the remainder, t, is known as the “tail.”
Try also defining the function length : {α:Typeu}→Listα→Nat that returns the length of a list,
and prove that it behaves as expected (for example, length(appendasbs)=lengthas+lengthbs).
For another example, we can define the type of binary trees:
Given the fundamental importance of inductive types in Lean, it should
not be surprising that there are a number of tactics designed to work
with them effectively. We describe some of them here.
The cases tactic works on elements of an inductively defined type,
and does what the name suggests: it decomposes the element according
to each of the possible constructors. In its most basic form, it is
applied to an element x in the local context. It then reduces the
goal to cases in which x is replaced by each of the constructions.
There are extra bells and whistles. For one thing, cases allows
you to choose the names for each alternative using a
with clause. In the next example, for example, we choose the name
m for the argument to succ, so that the second case refers to
succm. More importantly, the cases tactic will detect any items
in the local context that depend on the target variable. It reverts
these elements, does the split, and reintroduces them. In the example
below, notice that the hypothesis h:n≠0 becomes h:0≠0
in the first branch, and h:m+1≠0 in the second.
The syntax of the with is convenient for writing structured proofs.
Lean also provides a complementary case tactic, which allows you to focus on goal
assign variable names.
The case tactic is clever, in that it will match the constructor to the appropriate goal. For example, we can fill the goals above in the opposite order:
You can also use cases with an arbitrary expression. Assuming that
expression occurs in the goal, the cases tactic will generalize over
the expression, introduce the resulting universally quantified
variable, and case on that.
Think of this as saying “split on cases as to whether m+3*k is
zero or the successor of some number.” The result is functionally
equivalent to the following:
Notice that the expression m+3*k is erased by generalize; all
that matters is whether it is of the form 0 or n✝+1. This
form of cases will not revert any hypotheses that also mention
the expression in the equation (in this case, m+3*k). If such a
term appears in a hypothesis and you want to generalize over that as
well, you need to revert it explicitly.
If the expression you case on does not appear in the goal, the
cases tactic uses have to put the type of the expression into
the context. Here is an example:
The theorem Nat.lt_or_gemn says m<n ∨ m≥n, and it is
natural to think of the proof above as splitting on these two
cases. In the first branch, we have the hypothesis hlt:m<n, and
in the second we have the hypothesis hge:m≥n. The proof above
is functionally equivalent to the following:
Remember that if you open Classical, you can use the law of the
excluded middle for any proposition at all. But using type class
inference (see Type Classes), Lean can actually
find the relevant decision procedure, which means that you can use the
case split in a computable function.
Just as the cases tactic can be used to carry out proof by cases,
the induction tactic can be used to carry out proofs by
induction. The syntax is similar to that of cases, except that the
argument can only be a term in the local context. Here is an example:
openAmbiguous namespace `Nat`: it is interpreted as `_root_.Hidden.Nat` because this `open` occurs inside `namespace Hidden`, while `_root_.Nat` is silently not opened. Specify the namespace unambiguously, e.g. `_root_.Hidden.Nat`. The warning can sometimes also be addressed by moving the `open` outside of the surrounding `namespace`.Note: This linter can be disabled with `set_option linter.ambiguousOpen false`Nattheoremzero_add(n:Nat):0+n=n:=byn:Nat⊢ 0+n=ninductionnzero⊢ 0+zero=zerosucca✝:Nata_ih✝:0+a✝=a✝⊢ 0+a✝.succ=a✝.succ<;>zero⊢ 0+zero=zerosucca✝:Nata_ih✝:0+a✝=a✝⊢ 0+a✝.succ=a✝.succsimp[*,add_zero,add_succ]All goals completed! 🐙theoremsucc_add(mn:Nat):succm+n=succ(m+n):=bym:Natn:Nat⊢ m.succ+n=(m+n).succinductionnzerom:Nat⊢ m.succ+zero=(m+zero).succsuccm:Nata✝:Nata_ih✝:m.succ+a✝=(m+a✝).succ⊢ m.succ+a✝.succ=(m+a✝.succ).succ<;>zerom:Nat⊢ m.succ+zero=(m+zero).succsuccm:Nata✝:Nata_ih✝:m.succ+a✝=(m+a✝).succ⊢ m.succ+a✝.succ=(m+a✝.succ).succsimp[*,add_zero,add_succ]All goals completed! 🐙theoremadd_comm(mn:Nat):m+n=n+m:=bym:Natn:Nat⊢ m+n=n+minductionnzerom:Nat⊢ m+zero=zero+msuccm:Nata✝:Nata_ih✝:m+a✝=a✝+m⊢ m+a✝.succ=a✝.succ+m<;>zerom:Nat⊢ m+zero=zero+msuccm:Nata✝:Nata_ih✝:m+a✝=a✝+m⊢ m+a✝.succ=a✝.succ+msimp[*,add_zero,add_succ,succ_add,zero_add]All goals completed! 🐙theoremadd_assoc(mnk:Nat):m+n+k=m+(n+k):=bym:Natn:Natk:Nat⊢ m+n+k=m+(n+k)inductionkzerom:Natn:Nat⊢ m+n+zero=m+(n+zero)succm:Natn:Nata✝:Nata_ih✝:m+n+a✝=m+(n+a✝)⊢ m+n+a✝.succ=m+(n+a✝.succ)<;>zerom:Natn:Nat⊢ m+n+zero=m+(n+zero)succm:Natn:Nata✝:Nata_ih✝:m+n+a✝=m+(n+a✝)⊢ m+n+a✝.succ=m+(n+a✝.succ)simp[*,add_zero,add_succ]All goals completed! 🐙
endHidden
The induction tactic also supports user-defined induction principles with
multiple targets (aka major premises). This example uses Nat.mod.inductionOn, which has the following signature:
We close this section with one last tactic that is designed to
facilitate working with inductive types, namely, the injection
tactic. By design, the elements of an inductive type are freely
generated, which is to say, the constructors are injective and have
disjoint ranges. The injection tactic is designed to make use of
this fact:
We are almost done describing the full range of inductive definitions
accepted by Lean. So far, you have seen that Lean allows you to
introduce inductive types with any number of recursive
constructors. In fact, a single inductive definition can introduce an
indexed family of inductive types, in a manner we now describe.
An inductive family is an indexed family of types defined by a
simultaneous induction of the following form:
In contrast to an ordinary inductive definition, which constructs an
element of some Sortu, the more general version constructs a
function ... → Sortu, where “...” denotes a sequence of
argument types, also known as indices. Each constructor then
constructs an element of some member of the family. One example is the
definition of Vectαn, the type of vectors of elements of α
of length n:
Notice that the cons constructor takes an element of
Vectαn and returns an element of Vectα(n+1), thereby using an
element of one member of the family to build an element of another.
A more exotic example is given by the definition of the equality type in Lean:
For each fixed α:Sortu and a:α, this definition
constructs a family of types Eqax, indexed by x : α.
Notably, however, there is only one constructor, refl, which
is an element of Eqaa.
Intuitively, the only way to construct a proof of Eqax
is to use reflexivity, in the case where x is a.
Note that Eqaa is the only inhabited type in the family of types
Eqax. The elimination principle generated by Lean is as follows:
It is a remarkable fact that all the basic axioms for equality follow
from the constructor, refl, and the eliminator, Eq.rec. The
definition of equality is atypical, however; see the discussion in Axiomatic Details.
The recursor Eq.rec is also used to define substitution:
Actually, Lean compiles the match expressions using a definition based on generated helpers
such as Eq.casesOn and Eq.ndrec, which are themselves defined using Eq.rec.
Using the recursor or match with h₁:a=b, we may assume a and b are the same,
in which case, pb and pa are the same.
It is not hard to prove that Eq is symmetric and transitive.
In the following example, we prove symm and leave as exercises the theorems trans and congr (congruence).
In the type theory literature, there are further generalizations of
inductive definitions, for example, the principles of
induction-recursion and induction-induction. These are not
supported by Lean.
We have described inductive types and their syntax through
examples. This section provides additional information for those
interested in the axiomatic foundations.
We have seen that the constructor to an inductive type takes
parameters—intuitively, the arguments that remain fixed
throughout the inductive construction—and indices, the arguments
parameterizing the family of types that is simultaneously under
construction. Each constructor should have a type, where the
argument types are built up from previously defined types, the
parameter and index types, and the inductive family currently being
defined. The requirement is that if the latter is present at all, it
occurs only strictly positively. This means simply that any argument
to the constructor in which it occurs is a dependent arrow type in which the
inductive type under definition occurs only as the resulting type,
where the indices are given in terms of constants and previous
arguments.
Since an inductive type lives in Sortu for some u, it is
reasonable to ask which universe levels u can be instantiated
to. Each constructor c in the definition of a family C of
inductive types is of the form
c : (a : α) → (b : β[a]) → C a p[a,b]
where a is a sequence of data type parameters, b is the
sequence of arguments to the constructors, and p[a, b] are the
indices, which determine which element of the inductive family the
construction inhabits. (Note that this description is somewhat
misleading, in that the arguments to the constructor can appear in any
order as long as the dependencies make sense.) The constraints on the
universe level of C fall into two cases, depending on whether or
not the inductive type is specified to land in Prop (that is,
Sort0).
Let us first consider the case where the inductive type is not
specified to land in Prop. Then the universe level u is
constrained to satisfy the following:
For each constructor c as above, and each βk[a] in the sequence β[a], if βk[a] : Sort v, we have u ≥ v.
In other words, the universe level u is required to be at least as
large as the universe level of each type that represents an argument
to a constructor.
When the inductive type is specified to land in Prop, there are no
constraints on the universe levels of the constructor arguments. But
these universe levels do have a bearing on the elimination
rule. Generally speaking, for an inductive type in Prop, the
motive of the elimination rule is required to be in Prop.
There is an exception to this last rule: we are allowed to eliminate
from an inductively defined Prop to an arbitrary Sort when
there is only one constructor and each constructor argument is either
in Prop or an index. The intuition is that in this case the
elimination does not make use of any information that is not already
given by the mere fact that the type of argument is inhabited. This
special case is known as singleton elimination.
We have already seen singleton elimination at play in applications of
Eq.rec, the eliminator for the inductively defined equality
type. We can use an element h:Eqab to cast an element
h₂:pa to pb even when pa and pb are arbitrary types,
because the cast does not produce new data; it only reinterprets the
data we already have. Singleton elimination is also used with
heterogeneous equality and well-founded recursion, which will be
discussed in a the chapter on induction and recursion.
We now consider two generalizations of inductive types that are often
useful, which Lean supports by “compiling” them down to the more
primitive kinds of inductive types described above. In other words,
Lean parses the more general definitions, defines auxiliary inductive
types based on them, and then uses the auxiliary types to define the
ones we really want. Lean's equation compiler, described in the next
chapter, is needed to make use of these types
effectively. Nonetheless, it makes sense to describe the declarations
here, because they are straightforward variations on ordinary
inductive definitions.
First, Lean supports mutually defined inductive types. The idea is
that we can define two (or more) inductive types at the same time,
where each one refers to the other(s).
In this example, two types are defined simultaneously: a natural
number n is Even if it is 0 or one more than an Odd
number, and Odd if it is one more than an Even number.
In the exercises below, you are asked to spell out the details.
A mutual inductive definition can also be used to define the notation
of a finite tree with nodes labelled by elements of α:
With this definition, one can construct an element of Treeα by
giving an element of α together with a list of subtrees, possibly
empty. The list of subtrees is represented by the type TreeListα,
which is defined to be either the empty list, nil, or the
cons of a tree and an element of TreeListα.
This definition is inconvenient to work with, however. It would be
much nicer if the list of subtrees were given by the type
List(Treeα), especially since Lean's library contains a number of functions
and theorems for working with lists. One can show that the type
TreeListα is isomorphic to List(Treeα), but translating
results back and forth along this isomorphism is tedious.
In fact, Lean allows us to define the inductive type we really want:
This is known as a nested inductive type. It falls outside the
strict specification of an inductive type given in the last section
because Tree does not occur strictly positively among the
arguments to mk, but, rather, nested inside the List type
constructor. Lean then automatically builds the
isomorphism between TreeListα and List(Treeα) in its kernel,
and defines the constructors for Tree in terms of the isomorphism.
Try defining other operations on the natural numbers, such as
multiplication, the predecessor function (with pred0=0),
truncated subtraction (with n-m=0 when m is greater
than or equal to n), and exponentiation. Then try proving some
of their basic properties, building on the theorems we have already
proved.
Since many of these are already defined in Lean's core library, you
should work within a namespace named Hidden, or something like
that, in order to avoid name clashes.
Define some operations on lists, like a length function or the
reverse function. Prove some properties, such as the following:
a. length(xs++ys)=lengthxs+lengthys
b. length(reversexs)=lengthxs
c. reverse(reversexs)=xs
Define an inductive data type consisting of terms built up from the following constructors:
Recursively define a function that evaluates any such term with respect to an assignment of values to the variables.
Similarly, define the type of propositional formulas, as well as
functions on the type of such formulas: an evaluation function,
functions that measure the complexity of a formula, and a function
that substitutes another formula for a given variable.
In the previous chapter, we saw that inductive definitions provide a
powerful means of introducing new types in Lean. Moreover, the
constructors and the recursors provide the only means of defining
functions on these types. By the propositions-as-types correspondence,
this means that induction is the fundamental method of proof.
Lean provides natural ways of defining recursive functions, performing
pattern matching, and writing inductive proofs. It allows you to
define a function by specifying equations that it should satisfy, and
it allows you to prove a theorem by specifying how to handle various
cases that can arise. Behind the scenes, these descriptions are
“compiled” down to primitive recursors, using a procedure that we
refer to as the “equation compiler.” The equation compiler is not part
of the trusted code base; its output consists of terms that are
checked independently by the kernel.
The interpretation of schematic patterns is the first step of the
compilation process. We have seen that the casesOn recursor can
be used to define functions and prove theorems by cases, according to
the constructors involved in an inductively defined type. But
complicated definitions may use several nested casesOn
applications, and may be hard to read and understand. Pattern matching
provides an approach that is more convenient, and familiar to users of
functional programming languages.
Consider the inductively defined type of natural numbers. Every
natural number is either zero or succx, and so you can define
a function from the natural numbers to an arbitrary type by specifying
a value in each of those cases:
The equations used to define these functions hold definitionally:
openNatdefsub1:Nat→Nat|zero=>zero|succx=>xdefisZero:Nat→Bool|zero=>true|succVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x=>false
Because addition and the zero notation have been assigned the
[match_pattern] attribute, they can be used in pattern matching. Lean
simply normalizes these expressions until the constructors zero
and succ are exposed.
Pattern matching works with any inductive type, such as products and option types:
This provides a compact way of unpacking hypotheses that make use of logical connectives.
In all these examples, pattern matching was used to carry out a single
case distinction. More interestingly, patterns can involve nested
constructors, as in the following examples.
The equation compiler first splits on cases as to whether the input is
zero or of the form succx. It then does a case split on
whether x is of the form zero or succx. It determines
the necessary case splits from the patterns that are presented to it,
and raises an error if the patterns fail to exhaust the cases. Once
again, we can use arithmetic notation, as in the version below. In
either case, the defining equations hold definitionally.
You can write defsub2 : Nat→Nat :=funx=>matchxwith|0=>0|1=>0|x.succ.succ=>x#printsub2 to see how the function was compiled to
recursors. (Lean will tell you that sub2 has been defined in terms
of an internal auxiliary function, sub2.match_1, but you can print
that out too.) Lean uses these auxiliary functions to compile match expressions.
Actually, the definition above is expanded to
The equation compiler can process multiple arguments sequentially. For
example, it would be more natural to define the previous example as a
function of two arguments:
Notice also that, when the value of an argument is not needed in the
definition, you can use an underscore instead. This underscore is
known as a wildcard pattern, or an anonymous variable. In contrast
to usage outside the equation compiler, here the underscore does not
indicate an implicit argument. The use of underscores for wildcards is
common in functional programming languages, and so Lean adopts that
notation. The section on wildcards and overlapping patterns
expands on the notion of a wildcard, and the description of inaccessible patterns explains how
you can use implicit arguments in patterns as well.
As described in Inductive Types,
inductive data types can depend on parameters. The following example defines
the tail function using pattern matching. The argument α:Typeu
is a parameter and occurs before the colon to indicate it does not participate in the pattern matching.
Lean also allows parameters to occur after the :, but pattern matching on them requires an explicit match.
Despite the different placement of the parameter α in these two
examples, in both cases it is treated in the same way, in that it does
not participate in a case split.
Lean can also handle more complex forms of pattern matching, in which
arguments to dependent types pose additional constraints on the
various cases. Such examples of dependent pattern matching are
considered in the section on dependent pattern matching.
In the second presentation, the patterns overlap; for example, the
pair of arguments 0, 0 matches all three cases. But Lean handles
the ambiguity by using the first applicable equation, so in this example
the net result is the same. In particular, the following equations hold
definitionally:
deffoo:Nat→Nat→Nat|0,Variable name `n` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_nNote: This linter can be disabled with `set_option linter.unusedVariables false`n=>0|Variable name `m` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_mNote: This linter can be disabled with `set_option linter.unusedVariables false`m,0=>1|Variable name `m` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_mNote: This linter can be disabled with `set_option linter.unusedVariables false`m,Variable name `n` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_nNote: This linter can be disabled with `set_option linter.unusedVariables false`n=>2
You can check that this definition of foo satisfies the same
definitional identities as before.
Some functional programming languages support incomplete
patterns. In these languages, the interpreter produces an exception
or returns an arbitrary value for incomplete cases. We can simulate
the arbitrary value approach using the Inhabited type
class. Roughly, an element of Inhabitedα is a witness to the fact
that there is an element of α; in the chapter on type classes
we will see that Lean can be instructed that suitable
base types are inhabited, and can automatically infer that other
constructed types are inhabited. On this basis, the
standard library provides a default element, default, of
any inhabited type.
We can also use the type Optionα to simulate incomplete patterns.
The idea is to return somea for the provided patterns, and use
none for the incomplete cases. The following example demonstrates
both approaches.
The equation compiler is clever. If you leave out any of the cases in
the following definition, the error message will let you know what has
not been covered.
Here (a : α) is a sequence of parameters, (b : β) is the
sequence of arguments on which pattern matching takes place, and γ
is any type, which can depend on a and b. Each line should
contain the same number of patterns, one for each element of β. As we
have seen, a pattern is either a variable, a constructor applied to
other patterns, or an expression that normalizes to something of that
form (where the non-constructors are marked with the [match_pattern]
attribute). The appearances of constructors prompt case splits, with
the arguments to the constructors represented by the given
variables. In the section on dependent pattern matching,
we will see that some explicit terms in patterns are forced into a particular form
in order to make an expression type check, though they do not play a
role in pattern matching. These are called “inaccessible patterns” for
that reason. But we will not need to use such inaccessible patterns
before covering dependent pattern matching.
As we saw in the last section, the terms t₁, ..., tₙ can make use
of any of the parameters a, as well as any of the variables that
are introduced in the corresponding patterns. What makes recursion and
induction possible is that they can also involve recursive calls to
foo. In this section, we will deal with structural recursion, in
which the arguments to foo occurring on the right-hand side of the
=> are subterms of the patterns on the left-hand side. The idea is
that they are structurally smaller, and hence appear in the inductive
type at an earlier stage. Here are some examples of structural
recursion from the last chapter, now defined using the equation
compiler:
openNatdefadd:Nat→Nat→Nat|m,zero=>m|m,succn=>succ(addmn)theoremadd_zero(m:Nat):addmzero=m:=rfltheoremadd_succ(mn:Nat):addm(succn)=succ(addmn):=rfltheoremzero_add:∀n,addzeron=n|zero=>rfl|succn=>congrArgsucc(zero_addn)defmul:Nat→Nat→Nat|Variable name `n` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_nNote: This linter can be disabled with `set_option linter.unusedVariables false`n,zero=>zero|n,succm=>add(mulnm)n
The proof of zero_add makes it clear that proof by induction is
really a form of recursion in Lean.
The example above shows that the defining equations for add hold
definitionally, and the same is true of mul. The equation compiler
tries to ensure that this holds whenever possible, as is the case with
straightforward structural induction. In other situations, however,
reductions hold only propositionally, which is to say, they are
equational theorems that must be applied explicitly. The equation
compiler generates such theorems internally. They are not meant to be
used directly by the user; rather, the simp tactic
is configured to use them when necessary. The following
proof of zero_add works this way:
As with definition by pattern matching, parameters to a structural
recursion or induction may appear before the colon. Such parameters
are simply added to the local context before the definition is
processed. For example, the definition of addition may also be written
as follows:
Here, the value of the fib function at n+2 (which is
definitionally equal to succ(succn)) is defined in terms of the
values at n+1 (which is definitionally equivalent to succn)
and the value at n. This is a notoriously inefficient way of
computing the Fibonacci function, however, with an execution time that
is exponential in n. Here is a better way:
In both cases, Lean generates the auxiliary function fibFast.loop.
To handle structural recursion, the equation compiler uses
course-of-values recursion, using constants below and brecOn
that are automatically generated with each inductively defined
type. You can get a sense of how it works by looking at the types of
Nat.below and Nat.brecOn:
The type @Nat.belowC(3:Nat) is a data structure that stores elements of C0, C1, and C2.
The course-of-values recursion is implemented by Nat.brecOn. It enables us to define the value of a dependent
function of type (n:Nat)→Cn at a particular input n in terms of all the previous values of the function,
presented as an element of @Nat.belowCn.
The use of course-of-values recursion is one of the techniques the equation compiler uses to justify to
the Lean kernel that a function terminates. It does not affect the code generator which compiles recursive
functions as other functional programming language compilers. Recall that #evalfib <n> is exponential in <n>.
On the other hand, #reducefib <n> is efficient because it uses the definition sent to the kernel that
is based on the brecOn construction.
Lean creates an auxiliary declaration for each letrec. In the example above,
it created the declaration replicate.loop for the letrecloop occurring at replicate.
Note that, Lean “closes” the declaration by adding any local variable occurring in the
letrec declaration as additional parameters. For example, the local variable a occurs
at letrecloop.
You can also use letrec in tactic mode and for creating proofs by induction.
When structural recursion cannot be used, we can prove termination using well-founded recursion.
We need a well-founded relation and a proof that each recursive application is decreasing with respect to
this relation. Dependent type theory is powerful enough to encode and justify
well-founded recursion. Let us start with the logical background that
is needed to understand how it works.
Lean's standard library defines two predicates, Accra and
WellFoundedr, where r is a binary relation on a type α,
and a is an element of type α.
The first, Acc, is an inductively defined predicate. According to
its definition, Accrx is equivalent to
∀y,ryx→Accry. If you think of ryx as denoting a kind of order relation
y≺x, then Accrx says that x is accessible from below,
in the sense that all its predecessors are accessible. In particular,
if x has no predecessors, it is accessible. Given any type α,
we should be able to assign a value to each accessible element of
α, recursively, by assigning values to all its predecessors first.
The statement that r is well-founded, denoted WellFoundedr,
is exactly the statement that every element of the type is
accessible. By the above considerations, if r is a well-founded
relation on a type α, we should have a principle of well-founded
recursion on α, with respect to the relation r. And, indeed,
we do: the standard library defines WellFounded.fix, which serves
exactly that purpose.
There is a long cast of characters here, but the first block we have
already seen: the type, α, the relation, r, and the
assumption, h, that r is well-founded. The variable C
represents the motive of the recursive definition: for each element
x:α, we would like to construct an element of Cx. The
function F provides the inductive recipe for doing that: it tells
us how to construct an element Cx, given elements of Cy for
each predecessor y of x.
Note that WellFounded.fix works equally well as an induction
principle. It says that if ≺ is well-founded and you want to prove
∀x,Cx, it suffices to show that for an arbitrary x, if we
have ∀y,ryx→Cy, then we have Cx.
In the example above we use the modifier noncomputable because the code
generator currently does not support WellFounded.fix. The function
WellFounded.fix is another tool Lean uses to justify that a function
terminates.
Lean knows that the usual order < on the natural numbers is well
founded. It also knows a number of ways of constructing new well
founded orders from others, for example, using lexicographic order.
Here is essentially the definition of division on the natural numbers that is found in the standard library.
The definition is somewhat inscrutable. Here the recursion is on
x, and div.F x f : Nat → Nat returns the “divide by y”
function for that fixed x. You have to remember that the second
argument to div.F, the recipe for the recursion, is a function
that is supposed to return the divide by y function for all values
x₁ smaller than x.
In addition to being difficult to read, this definition of div does not lead to div82 being definitionally equal to 4:
When Lean encounters a recursive definition, it first
tries structural recursion, and only when that fails, does it fall
back on well-founded recursion. Lean uses the tactic decreasing_tactic
to show that the recursive applications are smaller. The auxiliary
proposition x-y<x in the example above should be viewed as a hint
for this tactic.
The elaborator also proves a set of equational lemmas about the recursive definition, allowing it to be manipulated without resorting to low-level lemmas about accessible relations.
The defining equation for div does not hold definitionally, but
we can unfold div using the unfold tactic. We use conv to select which
div application we want to unfold.
example(xy:Nat):divxy=if0<y∧y≤xthendiv(x-y)y+1else0:=byx:Naty:Nat⊢ divxy=if0<y∧y≤xthendiv(x-y)y+1else0-- unfold occurrence in the left-hand-side of the equation:conv=>x:Naty:Nat| divxy=if0<y∧y≤xthendiv(x-y)y+1else0lhsx:Naty:Nat| divxy;unfolddivx:Naty:Nat| ifh:0<y∧y≤xthenhavethis:=⋯;div(x-y)y+1else0rflAll goals completed! 🐙example(xy:Nat)(h:0<y∧y≤x):divxy=div(x-y)y+1:=byx:Naty:Nath:0<y∧y≤x⊢ divxy=div(x-y)y+1conv=>x:Naty:Nath:0<y∧y≤x| divxy=div(x-y)y+1lhsx:Naty:Nath:0<y∧y≤x| divxy;unfolddivx:Naty:Nath:0<y∧y≤x| ifh:0<y∧y≤xthenhavethis:=⋯;div(x-y)y+1else0simp[h]All goals completed! 🐙
The following example is similar: it converts any natural number to a
binary expression, represented as a list of 0's and 1's. We have to
provide evidence that the recursive call is
decreasing, which we do here with a sorry. The sorry does not
prevent the interpreter from evaluating the function successfully,
but #eval! must be used instead of #eval when a term contains sorry.
As a final example, we observe that Ackermann's function can be
defined directly, because it is justified by the well-foundedness of
the lexicographic order on the natural numbers. The termination_by clause
instructs Lean to use a lexicographic order. This clause is actually mapping
the function arguments to elements of type Nat×Nat. Then, Lean uses typeclass
resolution to synthesize an element of type WellFoundedRelation(Nat×Nat).
In many cases, Lean can automatically determine an appropriate lexicographical order.
Ackermann's function is one such case, so the termination_by clause is optional:
Note that a lexicographic order is used in the example above because the instance
WellFoundedRelation(α×β) uses a lexicographic order. Lean also defines the instance
Note that, auxiliary function go is recursive in this example, but takeWhile is not.
Once again, Lean can automatically recognize this pattern, so the termination_by clause is unnecessary:
By default, Lean uses the tactic decreasing_tactic to prove recursive applications are decreasing. The modifier decreasing_by allows us to provide our own tactic. Here is an example.
Note that decreasing_by is not replacement for termination_by, they complement each other. termination_by is used to specify a well-founded relation, and decreasing_by for providing our own tactic for showing recursive applications are decreasing. In the following example, we use both of them.
Recall that using sorry is equivalent to using a new axiom, and should be avoided. In the following example, we used the sorry to prove False.
The command #printaxiomsunsound shows that unsound depends on the unsound axiom sorryAx used to implement sorry.
Definition `unsound` is a proposition; use `theorem` instead of `def`Note: This linter can be disabled with `set_option linter.defProp false`defdeclaration uses `sorry`unsound(x:Nat):False:=unsound(x+1)decreasing_bysorryAll goals completed! 🐙unsound0 : False#checkunsound0
-- `unsound 0` is a proof of `False`'unsound' depends on axioms: [sorryAx]#printaxiomsunsound
'unsound' depends on axioms: [sorryAx]
Summary:
If there is no termination_by, a well-founded relation is derived (if possible) by selecting an argument and then using typeclass resolution to synthesize a well-founded relation for this argument's type.
If termination_by is specified, it maps the arguments of the function to a type α and type class resolution is again used. Recall that, the default instance for β×γ is a lexicographic order based on the well-founded relations for β and γ.
The default well-founded relation instance for Nat is (·<·).
By default, the tactic decreasing_tactic is used to show that recursive applications are smaller with respect to the selected well-founded relation. If decreasing_tactic fails, the error message includes the remaining goal ... |- G. Note that, the decreasing_tactic uses assumption. So, you can include a have-expression to prove goal G. You can also provide your own tactic using decreasing_by.
Lean generates bespoke induction principles for recursive functions. These induction principles follow the recursive structure of the function's definition, rather than the structure of the datatype. Proofs about functions typically follow the recursive structure of the function itself, so these induction principles allow statements about the function to be proved more conveniently.
For example, using the functional induction principle for ack to prove that the result is always greater than 0 requires one case for each arm of the pattern match in ack:
defack:Nat→Nat→Nat|0,y=>y+1|x+1,0=>ackx1|x+1,y+1=>ackx(ack(x+1)y)theoremack_gt_zero:acknm>0:=byn:Natm:Nat⊢ acknm>0fun_inductionackwith|case1y=>case1y:Nat⊢ y+1>0simpAll goals completed! 🐙|case2xih=>case2x:Natih:ackx1>0⊢ ackx1>0exactihAll goals completed! 🐙|case3xyih1ih2=>case3x:Naty:Natih1:ack(x+1)y>0ih2:ackx(ack(x+1)y)>0⊢ ackx(ack(x+1)y)>0simp[This simp argument is unused:ackHint: Omit it from the simp argument list.[apply]simp [*]Note: This linter can be disabled with `set_option linter.unusedSimpArgs false`ack,*]All goals completed! 🐙
The ackx1 in the goal corresponds to the value of ack applied to the pattern variables x+1 and 0 returned in the second case of ack.
This term is automatically simplified to the right-hand side.
Happily, the inductive hypothesis ih:ackx1>0 corresponds to the recursive call, which is exactly the answer returned in this case.
In case3case3x:Naty:Natih1:ack(x+1)y>0ih2:ackx(ack(x+1)y)>0⊢ ackx(ack(x+1)y)>0, the goal is:
The ackx(ack(x+1)y) in the goal corresponds to the value returned in the third case of ack, when ack applied to x+1 and y+1 has been reduced.
The inductive hypotheses ih1:ack(x+1)y>0 and ih2:ackx(ack(x+1)y)>0 correspond to the recursive calls, with ih1 matching the nested recursive call.
Once again, the induction hypothesis is suitable.
Using fun_inductionack results in goals and induction hypotheses that match the recursive structure of ack. As a result, the proof can be a single line:
theoremack_gt_zero:acknm>0:=byn:Natm:Nat⊢ acknm>0fun_inductionackcase1y✝:Nat⊢ y✝+1>0case2x✝:Natih1✝:ackx✝1>0⊢ ackx✝1>0case3x✝:Naty✝:Natih2✝:ack(x✝+1)y✝>0ih1✝:ackx✝(ack(x✝+1)y✝)>0⊢ ackx✝(ack(x✝+1)y✝)>0<;>case1y✝:Nat⊢ y✝+1>0case2x✝:Natih1✝:ackx✝1>0⊢ ackx✝1>0case3x✝:Naty✝:Natih2✝:ack(x✝+1)y✝>0ih1✝:ackx✝(ack(x✝+1)y✝)>0⊢ ackx✝(ack(x✝+1)y✝)>0simp[*,This simp argument is unused:ackHint: Omit it from the simp argument list.[apply]simp [*]Note: This linter can be disabled with `set_option linter.unusedSimpArgs false`ack]All goals completed! 🐙
There is also a fun_cases tactic which is analogous to the cases tactic.
It generates a case for each branch in a function's control flow.
Both it and fun_induction additionally provide assumptions that rule out the paths that were not taken.
This function f represents a five-way Boolean disjunction:
What makes this a mutual definition is that even is defined recursively in terms of odd, while odd is defined recursively in terms of even. Under the hood, this is compiled as a single recursive definition. The internally defined function takes, as argument, an element of a sum type, either an input to even, or an input to odd. It then returns an output appropriate to the input. To define that function, Lean uses a suitable well-founded measure. The internals are meant to be hidden from users; the canonical way to make use of such definitions is to use simp (or unfold), as we did above.
Mutual recursive definitions also provide natural ways of working with mutual and nested inductive types. Recall the definition of Even and Odd as mutual inductive predicates as presented before.
The constructors, even_zero, even_succ, and odd_succ provide positive means for showing that a number is even or odd. We need to use the fact that the inductive type is generated by these constructors to know that zero is not odd, and that the latter two implications reverse. As usual, the constructors are kept in a namespace that is named after the type being defined, and the command openEvenOdd allows us to access them more conveniently.
For another example, suppose we use a nested inductive type to define a set of terms inductively, so that a term is either a constant (with a name given by a string), or the result of applying a constant to a list of constants.
We can then use a mutual recursive definition to count the number of constants occurring in a term, as well as the number occurring in a list of terms.
As a final example, we define a function replaceConstabe that replaces a constant a with b in a term e, and then prove the number of constants is the same. Note that, our proof uses mutual recursion (aka induction).
All the examples of pattern matching we considered in the section on
pattern matching can easily be written using casesOn
and recOn. However, this is often not the case with indexed
inductive families such as Vectαn, since case splits impose
constraints on the values of the indices. Without the equation
compiler, we would need a lot of boilerplate code to define very
simple functions such as map, zip, and unzip using
recursors. To understand the difficulty, consider what it would take
to define a function tail which takes a vector
v : Vectα(n+1) and deletes the first element.
But what value should we return in the nil case? Something funny
is going on: if v has type Vectα(n+1), it can't be
nil, but it is not clear how to tell that to Vect.casesOn.
In the nil case, m is instantiated to 0, and
Nat.noConfusion makes use of the fact that 0=n+1 cannot
occur. Otherwise, v is of the form cons aas, and we can simply
return as, after casting it from a vector of length m to a
vector of length n.
The difficulty in defining tail is to maintain the relationships between the indices.
The hypothesis m=n+1 in tailAux is used to communicate the relationship
between n and the index associated with the minor premise.
Moreover, the 0=n+1 case is unreachable, and the canonical way to discard such
a case is to use Nat.noConfusion.
The tail function is, however, easy to define using recursive
equations, and the equation compiler generates all the boilerplate
code automatically for us. Here are a number of similar examples:
Note that we can omit recursive equations for “unreachable” cases such
as headnil. The automatically generated definitions for indexed
families are far from straightforward. For example:
The zipWith function is even more tedious to define by hand than the
tail function. We encourage you to try it, using Vect.recOn,
Vect.casesOn and Vect.noConfusion.
Sometimes an argument in a dependent matching pattern is not essential
to the definition, but nonetheless has to be included to specialize
the type of the expression appropriately. Lean allows users to mark
such subterms as inaccessible for pattern matching. These
annotations are essential, for example, when a term occurring in the
left-hand side is neither a variable nor a constructor application,
because these are not suitable targets for pattern matching. We can
view such inaccessible patterns as “don't care” components of the
patterns. You can declare a subterm inaccessible by writing
.(t). If the inaccessible pattern can be inferred, you can also write
_.
The following example, we declare an inductive type that defines the
property of “being in the image of f”. You can view an element of
the type ImageOffb as evidence that b is in the image of
f, whereby the constructor imf is used to build such
evidence. We can then define any function f with an “inverse”
which takes anything in the image of f to an element that is
mapped to it. The typing rules forces us to write fa for the
first argument, but this term is neither a variable nor a constructor
application, and plays no role in the pattern-matching definition. To
define the function inverse below, we have to mark fa
inaccessible.
In the example above, the inaccessible annotation makes it clear that
f is not a pattern matching variable.
Inaccessible patterns can be used to clarify and control definitions that
make use of dependent pattern matching. Consider the following
definition of the function Vect.add, which adds two vectors of
elements of a type, assuming that type has an associated addition
function:
inductiveVect(α:Typeu):Nat→Typeu|nil:Vectα0|cons:α→{n:Nat}→Vectαn→Vectα(n+1)defVect.add[Addα]:{n:Nat}→Vectαn→Vectαn→Vectαn|0,nil,nil=>nil|Variable name `n` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_nNote: This linter can be disabled with `set_option linter.unusedVariables false`n+1,consaas,consbbs=>cons(a+b)(addasbs)
The argument {n:Nat} appear after the colon, because it cannot
be held fixed throughout the definition. When implementing this
definition, the equation compiler starts with a case distinction as to
whether the first argument is 0 or of the form n+1. This is
followed by nested case splits on the next two arguments, and in each
case the equation compiler rules out the cases are not compatible with
the first pattern.
But, in fact, a case split is not required on the first argument; the
casesOn eliminator for Vect automatically abstracts this
argument and replaces it by 0 and n+1 when we do a case
split on the second argument. Using inaccessible patterns, we can prompt
the equation compiler to avoid the case split on n.
Marking the position as an inaccessible pattern tells the
equation compiler first, that the form of the argument should be
inferred from the constraints posed by the other arguments, and,
second, that the first argument should not participate in pattern
matching.
The inaccessible pattern .(_) can be written as _ for convenience.
As we mentioned above, the argument {n:Nat} is part of the
pattern matching, because it cannot be held fixed throughout the
definition. Rather than requiring that these discriminants be provided explicitly, Lean implicitly includes
these extra discriminants automatically for us.
This does not look very different from an ordinary pattern matching
definition, but the point is that a match can be used anywhere in
an expression, and with arbitrary arguments.
Lean uses the match construct internally to implement pattern-matching in all parts of the system.
Thus, all four of these definitions have the same net effect:
Open a namespace Hidden to avoid naming conflicts, and use the
equation compiler to define addition, multiplication, and
exponentiation on the natural numbers. Then use the equation
compiler to derive some of their basic properties.
Similarly, use the equation compiler to define some basic
operations on lists (like the reverse function) and prove
theorems about lists by induction (such as the fact that
reverse(reversexs)=xs for any list xs).
Define your own function to carry out course-of-value recursion on
the natural numbers. Similarly, see if you can figure out how to
define WellFounded.fix on your own.
Following the examples in the section on dependent pattern matching,
define a function that will append two vectors.
This is tricky; you will have to define an auxiliary function.
Consider the following type of arithmetic expressions. The idea is
that varn is a variable, vₙ, and constn is the
constant whose value is n.
defdeclaration uses `sorry`eval(v:Nat→Nat):Expr→Nat|constn=>sorry|varn=>vn|pluse₁e₂=>sorry|timese₁e₂=>sorrydefsampleVal:Nat→Nat|0=>5|1=>6|_=>0-- Try it out. You should get 47 here.-- #eval eval sampleVal sampleExpr
Implement “constant fusion,” a procedure that simplifies subterms like
5+7 to 12. Using the auxiliary function simpConst,
define a function “fuse”: to simplify a plus or a times, first
simplify the arguments recursively, and then apply simpConst to
try to simplify the result.
We have seen that Lean's foundational system includes inductive
types. We have, moreover, noted that it is a remarkable fact that it
is possible to construct a substantial edifice of mathematics based on
nothing more than the type universes, dependent arrow types, and inductive types;
everything else follows from those. The Lean standard library contains
many instances of inductive types (e.g., Nat, Prod, List),
and even the logical connectives are defined using inductive types.
Recall that a non-recursive inductive type that contains only one
constructor is called a structure or record. The product type is a
structure, as is the dependent product (Sigma) type.
In general, whenever we define a structure S, we usually
define projection functions that allow us to “destruct” each
instance of S and retrieve the values that are stored in its
fields. The functions Prod.fst and Prod.snd, which return the
first and second elements of a pair, are examples of such projections.
When writing programs or formalizing mathematics, it is not uncommon
to define structures containing many fields. The structure
command, available in Lean, provides infrastructure to support this
process. When we define a structure using this command, Lean
automatically generates all the projection functions. The
structure command also allows us to define new structures based on
previously defined ones. Moreover, Lean provides convenient notation
for defining instances of a given structure.
The structure command is essentially a “front end” for defining
inductive data types. Every structure declaration introduces a
namespace with the same name. The general form is as follows:
structure <name> <parameters> <parent-structures> where
<constructor> :: <fields>
Most parts are optional. Here is an example:
structurePoint(α:Typeu)wheremk::x:αy:α
Values of type Point are created using Point.mkab, and the
fields of a point p are accessed using Point.xp and
Point.yp (but p.x and p.y also work, see below).
The structure command also generates useful recursors and
theorems. Here are some of the constructions generated for the
declaration above.
-- a projection@Point.x : {α:Type u_1}→Pointα→α#check@Point.x
@Point.x : {α:Type u_1}→Pointα→α
-- a projection@Point.y : {α:Type u_1}→Pointα→α#check@Point.y
@Point.y : {α:Type u_1}→Pointα→α
If the constructor name is not provided, then a constructor is named
mk by default.
Here are some simple theorems and expressions that use the generated
constructions. As usual, you can avoid the prefix Point by using
the command openPoint.
The dot notation is convenient not just for accessing the projections
of a record, but also for applying functions defined in a namespace
with the same name. Recall from the Conjunction section if p
has type Point, the expression p.foo is interpreted as
Point.foo p, assuming that the first non-implicit argument to
foo has type Point. The expression p.addq is therefore
shorthand for Point.add p q in the example below.
In the next chapter, you will learn how to define a function like
add so that it works generically for elements of Pointα
rather than just PointNat, assuming α has an associated
addition operation.
More generally, given an expression p.foo x y z where p : Point,
Lean will insert p at the first argument to Point.foo of type
Point. For example, with the definition of scalar multiplication
below, p.smul3 is interpreted as Point.smul3p.
We have been using constructors to create elements of a structure
type. For structures containing many fields, this is often
inconvenient, because we have to remember the order in which the
fields were defined. Lean therefore provides the following alternative
notations for defining elements of a structure type.
The suffix : structure-type can be omitted whenever the name of
the structure can be inferred from the expected type. For example, we
use this notation to define “points.” The order that the fields are
specified does not matter, so all the expressions below define the
same point.
Fields can be marked as implicit using curly braces.
Implicit fields become implicit parameters to the constructor.
If the value of a field is not specified, Lean tries to infer it. If
the unspecified fields cannot be inferred, Lean flags an error
indicating the corresponding placeholder could not be synthesized.
`MyStruct`: universes `u`, `v` only occur together. This usually means there is a `max` expression in the type where none of these universes appear on their own.Note: This linter can be disabled with `set_option linter.checkUnivs false`structureMyStructwhere{α:Typeu}{β:Typev}a:αb:β{α:=Nat,β:=Bool,a:=10,b:=true} : MyStruct#check{a:=10,b:=true:MyStruct}
Record update is another common operation which amounts to creating
a new record object by modifying the value of one or more fields in an
old one. Lean allows you to specify that unassigned fields in the
specification of a record should be taken from a previously defined
structure object s by adding the annotation s with before the field
assignments. If more than one record object is provided, then they are
visited in order until Lean finds one that contains the unspecified
field. Lean raises an error if any of the field names remain
unspecified after all the objects are visited.
structurePoint(α:Typeu)wherex:αy:αderivingReprdefp:PointNat:={x:=1,y:=2}{ x := 1, y := 3 }#eval{pwithy:=3}
Type classes were introduced as a principled way of enabling
ad-hoc polymorphism in functional programming languages. We first observe that it
would be easy to implement an ad-hoc polymorphic function (such as addition) if the
function simply took the type-specific implementation of addition as an argument
and then called that implementation on the remaining arguments. For example,
suppose we declare a structure in Lean to hold implementations of addition.
In the above Lean code, the field add has type
Add.add:{α:Type}→Addα→α→α→α
where the curly braces around the type α mean that it is an implicit argument.
We could implement double by:
Note that you can double a natural number n by double{add:=Nat.add}n.
Of course, it would be highly cumbersome for users to manually pass the
implementations around in this way.
Indeed, it would defeat most of the potential benefits of ad-hoc
polymorphism.
The main idea behind type classes is to make arguments such as Addα implicit,
and to use a database of user-defined instances to synthesize the desired instances
automatically through a process known as typeclass resolution. In Lean, by changing
structure to class in the example above, the type of Add.add becomes:
where the square brackets indicate that the argument of type Addα is instance implicit,
i.e. that it should be synthesized using typeclass resolution. This version of
add is the Lean analogue of the Haskell term add :: Add a => a -> a -> a.
Similarly, we can register instances by:
Then for n : Nat and m : Nat, the term Add.addnm triggers typeclass resolution with
the goal of AddNat, and typeclass resolution will synthesize the instance for Nat above.
We can now reimplement double using an instance implicit by:
In general, instances may depend on other instances in complicated ways. For example,
you can declare an instance stating that if α has addition, then Arrayα
has addition:
Note that (·+·) is notation for funxy=>x+y in Lean.
The example above demonstrates how type classes are used to overload notation.
Now, we explore another application. We often need an arbitrary element of a given type.
Recall that types may not have any elements in Lean.
It often happens that we would like a definition to return an arbitrary element in a “corner case.”
For example, we may like the expression headxs to be of type α when xs is of type Listα.
Similarly, many theorems hold under the additional assumption that a type is not empty.
For example, if α is a type, ∃x:α,x=x is true only if α is not empty.
The standard library defines a type class Inhabited to enable type class inference to infer a
“default” element of an inhabited type.
Let us start with the first step of the program above, declaring an appropriate class:
Note Inhabited.default doesn't have any explicit arguments.
An element of the class Inhabitedα is simply an expression of the form Inhabited.mkx, for some element x : α.
The projection Inhabited.default will allow us to “extract” such an element of α from an element of Inhabitedα.
Now we populate the class with some instances:
If that were the extent of type class inference, it would not be all that impressive;
it would be simply a mechanism of storing a list of instances for the elaborator to find in a lookup table.
What makes type class inference powerful is that one can chain instances. That is,
an instance declaration can in turn depend on an implicit instance of a type class.
This causes class inference to chain through instances recursively, backtracking when necessary, in a Prolog-like search.
For example, the following definition shows that if two types α and β are inhabited, then so is their product:
As an exercise, try defining default instances for other types, such as List and Sum types.
The Lean standard library contains the definition inferInstance. It has type {α:Sortu}→[i:α]→α,
and is useful for triggering the type class resolution procedure when the expected type is an instance.
Definition `foo` of class type is semireducible. Most type class instances should be instance-reducible, so consider marking thisdefinition with `@[instance_reducible]`. If it is intentionally semireducible, this warning can be disabled with `set_option warn.classDefReducibility false`.deffoo:Inhabited(Nat×Nat):=inferInstancetheoremex:foo.default=(default,default):=rfl
You can use the command #print to inspect how simple inferInstance is.
The polymorphic method toString has type {α:Typeu}→[ToStringα]→α→String. You implement the instance
for your own types and use chaining to convert complex values into strings. Lean comes with ToString instances
for most builtin types.
Lean elaborates the terms (2:Nat) and (2:Rational) as
@OfNat.ofNatNat2(@instOfNatNat2) and
@OfNat.ofNatRational2(@instOfNatRational2) respectively.
We say the numerals 2 occurring in the elaborated terms are raw natural numbers.
You can input the raw natural number 2 using the macro nat_lit2.
The OfNat instance is parametric on the numeral. So, you can define instances for particular numerals.
The second argument is often a variable as in the example above, or a raw natural number.
By default, Lean only tries to synthesize an instance InhabitedT when the term T is known and does not
contain missing parts. The following command produces the error
typeclass instance problem is stuck, it is often due to metavariables because the type has a missing part (i.e., the _).
You can view the parameter of the type class Inhabited as an input value for the type class synthesizer.
When a type class has multiple parameters, you can mark some of them as output parameters.
Lean will start type class synthesizer even when these parameters have missing parts.
In the following example, we use output parameters to define a heterogeneous polymorphic
multiplication.
The parameters α and β are considered input parameters and γ an output one.
Given an application hMulab, after the types of a and b are known, the type class
synthesizer is invoked, and the resulting type is obtained from the output parameter γ.
In the example above, we defined two instances. The first one is the homogeneous
multiplication for natural numbers. The second is the scalar multiplication for arrays.
Note that you chain instances and generalize the second instance.
You can use our new scalar array multiplication instance on arrays of type Arrayβ
with a scalar of type α whenever you have an instance HMulαβγ.
In the last #eval, note that the instance was used twice on an array of arrays.
Output parameters are ignored during instance synthesis. Even when instance synthesis occurs in a
context in which the values of output parameters are already determined, their values are ignored.
Once an instance is found using its input parameters, Lean ensures that the already-known values of
the output parameters match those which were found.
Lean also features semi-output parameters, which have some features of input parameters
and some features of output parameters. Like input parameters, semi-output parameters are considered
when selecting instances. Like output parameters, they can be used to instantiate unknown values.
However, they do not do so uniquely. Instance synthesis with semi-output parameters can be more difficult
to predict, because the order in which instances are considered can determine which is selected, but it is
also more flexible.
In the class HMul, the parameters α and β are treated as input values.
Thus, type class synthesis only starts after these two types are known. This may often
be too restrictive.
classHMul(α:Typeu)(β:Typev)(γ:outParam(Typew))wherehMul:α→β→γexportHMul(hMul)instance:HMulIntIntIntwherehMul:=Int.muldefxs:ListInt:=[1,2,3]/--
error: typeclass instance problem is stuck
HMul Int ?m.2 (?m.11 y)
Note: Lean will not try to resolve this typeclass instance problem because the second type argument to `HMul` is a metavariable. This argument must be fully determined before Lean will try to resolve the typeclass.
Hint: Adding type annotations and supplying implicit arguments to functions can give Lean more information for typeclass resolution. For example, if you have a variable `x` that you intend to be a `Nat`, but Lean reports it as having an unresolved type like `?m`, replacing `x` with `(x : Nat)` can get typeclass resolution un-stuck.
-/#guard_msgs(error)in#evalfuny=>xs.map(funx=>hMulxy)
endEx
The instance HMul is not synthesized by Lean because the type of y has not been provided.
However, it is natural to assume that the type of y and x should be the same in
this kind of situation. We can achieve exactly that using default instances.
By tagging the instance above with the attribute [default_instance], we are instructing Lean
to use this instance on pending type class synthesis problems.
The actual Lean implementation defines homogeneous and heterogeneous classes for arithmetical operators.
Moreover, a+b, a*b, a-b, a/b, and a%b are notations for the heterogeneous versions.
The instance OfNatNatn is the default instance (with priority 100) for the OfNat class. This is why the numeral
2 has type Nat when the expected type is not known. You can define default instances with higher
priority to override the builtin ones.
Priorities are also useful to control the interaction between different default instances.
For example, suppose xs has type Listα. When elaborating xs.map(funx=>2*x), we want the homogeneous instance for multiplication
to have higher priority than the default instance for OfNatα2. This is particularly important when we have implemented only the instance
HMulααα, and did not implement HMulNatαα.
Now, we reveal how the notation a * b is defined in Lean.
Type classes are implemented using attributes in Lean. Thus, you can
use the local modifier to indicate that they only have effect until
the current section or namespace is closed, or until the end
of the current file.
structurePointwherex:Naty:Natsectionlocalinstance:AddPointwhereaddab:={x:=a.x+b.x,y:=a.y+b.y}defdouble(p:Point):=p+pend-- instance `Add Point` is not active anymore/--
error: failed to synthesize instance of type class
HAdd Point Point ?m.5
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
-/#guard_msgsindeftriple(p:Point):=p+p+p
You can also temporarily disable an instance using the attribute command
until the current section or namespace is closed, or until the end
of the current file.
structurePointwherex:Naty:NatinstanceaddPoint:AddPointwhereaddab:={x:=a.x+b.x,y:=a.y+b.y}defdouble(p:Point):=p+pattribute[-instance]addPoint/--
error: failed to synthesize instance of type class
HAdd Point Point ?m.5
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
-/#guard_msgsindeftriple(p:Point):=p+p+p-- Error: failed to synthesize instance
We recommend you only use this command to diagnose problems.
You can also declare scoped instances in namespaces. This kind of instance is
only active when you are inside of the namespace or open the namespace.
structurePointwherex:Naty:NatnamespacePointscopedinstance:AddPointwhereaddab:={x:=a.x+b.x,y:=a.y+b.y}defdouble(p:Point):=p+pendPoint-- instance `Add Point` is not active anymore/--
error: failed to synthesize instance of type class
HAdd Point Point ?m.3
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
-/#guard_msgs(error)infunp=>sorry : (p:Point)→?m.6p#checkfun(p:Point)=>p+p+p
funp=>sorry : (p:Point)→?m.6p
namespacePoint-- instance `Add Point` is active againfunp=>p+p+p : Point→Point#checkfun(p:Point)=>p+p+p
Let us consider another example of a type class defined in the
standard library, namely the type class of Decidable
propositions. Roughly speaking, an element of Prop is said to be
decidable if we can decide whether it is true or false. The
distinction is only useful in constructive mathematics; classically,
every proposition is decidable. But if we use the classical principle,
say, to define a function by cases, that function will not be
computable. Algorithmically speaking, the Decidable type class can
be used to infer a procedure that effectively determines whether or
not the proposition is true. As a result, the type class supports such
computational definitions when they are possible while at the same
time allowing a smooth transition to the use of classical definitions
and classical reasoning.
In the standard library, Decidable is defined formally as follows:
Logically speaking, having an element t : Decidablep is stronger
than having an element t':p∨¬p; it enables us to define values
of an arbitrary type depending on the truth value of p. For
example, for the expression ifpthenaelseb to make sense, we
need to know that p is decidable. That expression is syntactic
sugar for itepab, where ite is defined as follows:
That is, in ditecte, we can assume hc : c in the “then”
branch, and hnc : ¬c in the “else” branch. To make dite more
convenient to use, Lean allows us to write ifh:cthentelsee
instead of ditec(funh:c=>th)(funh:¬c=>eh).
Without classical logic, we cannot prove that every proposition is
decidable. But we can prove that certain propositions are
decidable. For example, we can prove the decidability of basic
operations like equality and comparisons on the natural numbers and
the integers. Moreover, decidability is preserved under propositional
connectives:
Turning on implicit arguments shows that the elaborator has inferred
the decidability of the proposition x<a∨x>b, simply by
applying appropriate instances.
With the classical axioms, we can prove that every proposition is
decidable. You can import the classical axioms and make the generic
instance of decidability available by opening the Classical namespace.
Thereafter Decidablep has an instance for every p.
Thus all theorems in the library
that rely on decidability assumptions are freely available when you
want to reason classically. In Axioms and Computation,
we will see that using the law of the
excluded middle to define functions can prevent them from being used
computationally. Thus, the standard library assigns a low priority to
the propDecidable instance.
This guarantees that Lean will favor other instances and fall back on
propDecidable only after other attempts to infer decidability have
failed.
The Decidable type class also provides a bit of small-scale
automation for proving theorems. The standard library introduces the
tactic decide that uses the Decidable instance to solve simple goals,
as well as a function decide that uses a Decidable instance to compute the
corresponding Bool.
They work as follows. The expression decidep tries to infer a
decision procedure for p, and, if it is successful, evaluates to
either true or false. In particular, if p is a true closed
expression, decidep will reduce definitionally to the Boolean true.
On the assumption that decidep=true holds, of_decide_eq_true
produces a proof of p. The tactic decide puts it all together to
prove a target p. By the previous observations,
decide will succeed any time the inferred decision procedure
for p has enough information to evaluate, definitionally, to the isTrue case.
If you are ever in a situation where you need to supply an expression
that Lean can infer by type class inference, you can ask Lean to carry
out the inference using inferInstance:
Definition `foo` of class type is semireducible. Most type class instances should be instance-reducible, so consider marking thisdefinition with `@[instance_reducible]`. If it is intentionally semireducible, this warning can be disabled with `set_option warn.classDefReducibility false`.deffoo:AddNat:=inferInstanceDefinition `bar` of class type is semireducible. Most type class instances should be instance-reducible, so consider marking thisdefinition with `@[instance_reducible]`. If it is intentionally semireducible, this warning can be disabled with `set_option warn.classDefReducibility false`.defbar:Inhabited(Nat→Nat):=inferInstance@inferInstance : {α:Sort u_1}→[i:α]→α#check@inferInstance
Sometimes Lean can't find an instance because the class is buried
under a definition. For example, Lean cannot
find an instance of Inhabited(Setα). We can declare one
explicitly:
defSet(α:Typeu):=α→Prop/--
error: failed to synthesize instance of type class
Inhabited (Set α)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
-/#guard_msgsinexample:Inhabited(Setα):=inferInstanceinstance:Inhabited(Setα):=inferInstanceAs(Inhabited(α→Prop))
At times, you may find that the type class inference fails to find an
expected instance, or, worse, falls into an infinite loop and times
out. To help debug in these situations, Lean enables you to request a
trace of the search:
set_optiontrace.Meta.synthInstancetrue
If you are using VS Code, you can read the results by hovering over
the relevant theorem or definition, or opening the messages window
with CtrlShiftEnter.
You can also limit the search using the following options:
Option synthInstance.maxHeartbeats specifies the maximum amount of
heartbeats per typeclass resolution problem. A heartbeat is the number of
(small) memory allocations (in thousands), 0 means there is no limit.
Option synthInstance.maxSize is the maximum number of instances used
to construct a solution in the type class instance synthesis procedure.
Remember also that in both the VS Code and Emacs editor modes, tab
completion works in set_option, to help you find suitable options.
As noted above, the type class instances in a given context represent
a Prolog-like program, which gives rise to a backtracking search. Both
the efficiency of the program and the solutions that are found can
depend on the order in which the system tries the instance. Instances
which are declared last are tried first. Moreover, if instances are
declared in other modules, the order in which they are tried depends
on the order in which namespaces are opened. Instances declared in
namespaces which are opened later are tried earlier.
You can change the order that type class instances are tried by
assigning them a priority. When an instance is declared, it is
assigned a default priority value. You can assign other priorities
when defining an instance. The following example illustrates how this
is done:
The most basic type of coercion maps elements of one type to another. For example, a coercion from Nat to Int allows us to view any element n : Nat as an element of Int. But some coercions depend on parameters; for example, for any type α, we can view any element as : Listα as an element of Setα, namely, the set of elements occurring in the list. The corresponding coercion is defined on the “family” of types Listα, parameterized by α.
Lean allows us to declare three kinds of coercions:
from a family of types to another family of types
from a family of types to the class of sorts
from a family of types to the class of function types
The first kind of coercion allows us to view any element of a member of the source family as an element of a corresponding member of the target family. The second kind of coercion allows us to view any element of a member of the source family as a type. The third kind of coercion allows us to view any element of the source family as a function. Let us consider each of these in turn.
In Lean, coercions are implemented on top of the type class resolution framework. We define a coercion from α to β by declaring an instance of Coeαβ. For example, we can define a coercion from Bool to Prop as follows:
We can define a coercion from Listα to Setα as follows:
defSet(α:Typeu):=α→PropdefSet.empty{α:Typeu}:Setα:=fun_=>FalsedefSet.mem(a:α)(s:Setα):Prop:=sadefSet.singleton(a:α):Setα:=funx=>x=adefSet.union(ab:Setα):Setα:=funx=>ax∨bxnotation"{ "a" }"=>Set.singletonainfix:55" ∪ "=>Set.union
We can use the notation ↑ to force a coercion to be introduced in a particular place. It is also helpful to make our intent clear, and work around limitations of the coercion resolution system.
defSet(α:Typeu):=α→PropdefSet.empty{α:Typeu}:Setα:=fun_=>FalsedefSet.mem(a:α)(s:Setα):Prop:=sadefSet.singleton(a:α):Setα:=funx=>x=adefSet.union(ab:Setα):Setα:=funx=>ax∨bxnotation"{ "a" }"=>Set.singletonainfix:55" ∪ "=>Set.uniondefList.toSet:Listα→Setα|[]=>Set.empty|a::as=>{a}∪as.toSetinstance:Coe(Listα)(Setα)wherecoea:=a.toSet
Lean also supports dependent coercions using the type class CoeDep. For example, we cannot coerce arbitrary propositions to Bool, only the ones that implement the Decidable typeclass.
Lean will also chain (non-dependent) coercions as necessary. Actually, the type class CoeT is the transitive closure of Coe.
Let us now consider the second kind of coercion. By the class of sorts, we mean the collection of universes Typeu. A coercion of the second kind is of the form:
c : (x1 : A1) → ... → (xn : An) → F x1 ... xn → Type u
where F is a family of types as above. This allows us to write s : t whenever t is of type F a₁ ... aₙ. In other words, the coercion allows us to view the elements of F a₁ ... aₙ as types. This is very useful when defining algebraic structures in which one component, the carrier of the structure, is a Type. For example, we can define a semigroup as follows:
In other words, a semigroup consists of a type, carrier, and a multiplication, mul, with the property that the multiplication is associative. The instance command allows us to write a*b instead of Semigroup.mulSab whenever we have ab : S.carrier; notice that Lean can infer the argument S from the types of a and b. The function Semigroup.carrier maps the class Semigroup to the sort Typeu:
It is the coercion that makes it possible to write (abc:S). Note that, we define an instance of CoeSortSemigroup(Typeu) instead of CoeSemigroup(Typeu).
By the class of function types, we mean the collection of Pi types (z:B)→C. The third kind of coercion has the form:
c : (x₁ : A₁) → ... → (xₙ : Aₙ) → (y : F x₁ ... xₙ) → (z : B) → C
where F is again a family of types and B and C can depend on x₁, ..., xₙ, y. This makes it possible to write t s whenever t is an element of F a₁ ... aₙ. In other words, the coercion enables us to view elements of F a₁ ... aₙ as functions. Continuing the example above, we can define the notion of a morphism between semigroups S1 and S2. That is, a function from the carrier of S1 to the carrier of S2 (note the implicit coercion) that respects the multiplication. The projection Morphism.mor takes a morphism to the underlying function:
With the coercion in place, we can write f(a*a*a) instead of f.mor(a*a*a). When the Morphism, f, is used where a function is expected, Lean inserts the coercion. Similar to CoeSort, we have yet another class CoeFun for this class of coercions. The parameter γ is used to specify the function type we are coercing to. This type may depend on the type we are coercing from.
Inside a tactic block, one can use the keyword conv to enter
conversion mode. This mode allows to travel inside assumptions and
goals, even inside function abstractions and dependent arrows, to apply rewriting or
simplifying steps.
As a first example, let us prove example
(abc:Nat):a*(b*c)=a*(c*b)
(examples in this file are somewhat artificial since
other tactics could finish them immediately). The naive
first attempt is to enter tactic mode and try rw[Nat.mul_comm]. But this
transforms the goal into b*c*a=a*(c*b), after commuting the
very first multiplication appearing in the term. There are several
ways to fix this issue, and one way is to use a more precise tool:
the conversion mode. The following code block shows the current target
after each line.
The above snippet shows three navigation commands:
lhs navigates to the left-hand side of a relation (equality, in this case).
There is also a rhs to navigate to the right-hand side.
congr creates as many targets as there are (nondependent and explicit) arguments to the current head function
(here the head function is multiplication).
Once arrived at the relevant target, we can use rw as in normal
tactic mode.
The second main reason to use conversion mode is to rewrite under
binders. Suppose we want to prove example
(funx:Nat=>0+x)=(funx=>x).
The naive first attempt is to enter tactic mode and try
rw[Nat.zero_add]. But this fails with a frustrating
error: tactic 'rewrite' failed, did not find instance of the pattern
in the target expression
0 + ?n
⊢ (fun x => 0 + x) = fun x => x
The solution is:
example:(funx:Nat=>0+x)=(funx=>x):=by⊢ (funx=>0+x)=funx=>xconv=>| (funx=>0+x)=funx=>xlhs| funx=>0+xintroxx:Nat| 0+xrw[Nat.zero_add]x:Nat| x
where introx is the navigation command entering inside the fun binder.
Note that this example is somewhat artificial, one could also do:
enter [1, x, 2, y] iterate arg and intro with the given arguments.
done fail if there are unsolved goals.
trace_state display the current tactic state.
whnf put term in weak head normal form.
tactic => <tactic sequence> go back to regular tactic mode. This
is useful for discharging goals not supported by conv mode, and
applying custom congruence and extensionality lemmas.
We have seen that the version of the Calculus of Constructions that
has been implemented in Lean includes dependent function types,
inductive types, and a hierarchy of universes that starts with an
impredicative, proof-irrelevantProp at the bottom. In this
chapter, we consider ways of extending the CIC with additional axioms
and rules. Extending a foundational system in such a way is often
convenient; it can make it possible to prove more theorems, as well as
make it easier to prove theorems that could have been proved
otherwise. But there can be negative consequences of adding additional
axioms, consequences which may go beyond concerns about their
correctness. In particular, the use of axioms bears on the
computational content of definitions and theorems, in ways we will
explore here.
Lean is designed to support both computational and classical
reasoning. Users that are so inclined can stick to a “computationally
pure” fragment, which guarantees that closed expressions in the system
evaluate to canonical normal forms. In particular, any closed
computationally pure expression of type Nat, for example, will
reduce to a numeral.
Lean's standard library defines an additional axiom, propositional
extensionality, and a quotient construction which in turn implies the
principle of function extensionality. These extensions are used, for
example, to develop theories of sets and finite sets. We will see
below that using these theorems can block evaluation in Lean's kernel,
so that closed terms of type Nat no longer evaluate to numerals. But
Lean erases types and propositional information when compiling
definitions to executable code, and since
these axioms only add new propositions, they are compatible with that
computational interpretation. Even computationally inclined users may
wish to use the classical law of the excluded middle to reason about
computation. This also blocks evaluation in the kernel, but it is
compatible with compiled code.
The standard library also defines a choice principle that is entirely
antithetical to a computational interpretation, since it magically
produces “data” from a proposition asserting its existence. Its use is
essential to some classical constructions, and users can import it
when needed. But expressions that use this construction to produce
data do not have computational content, and in Lean we are required to
mark such definitions as noncomputable to flag that fact.
Using a clever trick (known as Diaconescu's theorem), one can use
propositional extensionality, function extensionality, and choice to
derive the law of the excluded middle. As noted above, however, use of
the law of the excluded middle is still compatible with
compilation, as are other classical principles, as
long as they are not used to manufacture data.
To summarize, then, on top of the underlying framework of universes,
dependent function types, and inductive types, the standard library
adds three additional components:
the axiom of propositional extensionality
a quotient construction, which implies function extensionality
a choice principle, which produces data from an existential proposition.
The first two of these block normalization within Lean, but are
compatible with code generation, whereas the third is not amenable
to computational interpretation. We will spell out the details more
precisely below.
For most of its history, mathematics was essentially computational:
geometry dealt with constructions of geometric objects, algebra was
concerned with algorithmic solutions to systems of equations, and
analysis provided means to compute the future behavior of systems
evolving over time. From the proof of a theorem to the effect that
“for every x, there is a y such that ...”, it was generally
straightforward to extract an algorithm to compute such a y given
x.
In the nineteenth century, however, increases in the complexity of
mathematical arguments pushed mathematicians to develop new styles of
reasoning that suppress algorithmic information and invoke
descriptions of mathematical objects that abstract away the details of
how those objects are represented. The goal was to obtain a powerful
“conceptual” understanding without getting bogged down in
computational details, but this had the effect of admitting
mathematical theorems that are simply false on a direct
computational reading.
There is still fairly uniform agreement today that computation is
important to mathematics. But there are different views as to how best
to address computational concerns. From a constructive point of
view, it is a mistake to separate mathematics from its computational
roots; every meaningful mathematical theorem should have a direct
computational interpretation. From a classical point of view, it is
more fruitful to maintain a separation of concerns: we can use one
language and body of methods to write computer programs, while
maintaining the freedom to use nonconstructive theories and methods
to reason about them. Lean is designed to support both of these
approaches. Core parts of the library are developed constructively,
but the system also provides support for carrying out classical
mathematical reasoning.
Computationally, the purest part of dependent type theory avoids the
use of Prop entirely. Inductive types and dependent function types
can be viewed as data types, and terms of these types can be
“evaluated” by applying reduction rules until no more rules can be
applied. In principle, any closed term (that is, term with no free
variables) of type Nat should evaluate to a numeral, succ(…(succzero)…).
Introducing a proof-irrelevant Prop and marking theorems
irreducible represents a first step towards separation of
concerns. The intention is that elements of a type p : Prop should
play no role in computation, and so the particular construction of a
term prf : p is “irrelevant” in that sense. One can still define
computational objects that incorporate elements of type Prop; the
point is that these elements can help us reason about the effects of
the computation, but can be ignored when we extract “code” from the
term. Elements of type Prop are not entirely innocuous,
however. They include equations s=t:α for any type α, and
such equations can be used as casts, to type check terms. Below, we
will see examples of how such casts can block computation in the
system. However, computation is still possible under an evaluation
scheme that erases propositional content, ignores intermediate typing
constraints, and reduces terms until they reach a normal form. This is
precisely what Lean's virtual machine does.
Having adopted a proof-irrelevant Prop, one might consider it
legitimate to use, for example, the law of the excluded middle,
p∨¬p, where p is any proposition. Of course, this, too, can block
computation according to the rules of CIC, but it does not prevent the generation
of executable code, as described above. It is only the choice
principles discussed in the section on choice that completely erase the
distinction between the proof-irrelevant and data-relevant parts of
the theory.
It asserts that when two propositions imply one another, they are
actually equal. This is consistent with set-theoretic interpretations
in which any element a : Prop is either empty or the singleton set
\{\ast\}, for some distinguished element \ast. The axiom has the
effect that equivalent propositions can be substituted for one another
in any context:
Similar to propositional extensionality, function extensionality
asserts that any two functions of type (x:α)→βx that agree on
all their inputs are equal:
From a classical, set-theoretic perspective, this is exactly what it
means for two functions to be equal. This is known as an “extensional”
view of functions. From a constructive perspective, however, it is
sometimes more natural to think of functions as algorithms, or
computer programs, that are presented in some explicit way. It is
certainly the case that two computer programs can compute the same
answer for every input despite the fact that they are syntactically
quite different. In much the same way, you might want to maintain a
view of functions that does not force you to identify two functions
that have the same input / output behavior. This is known as an
“intensional” view of functions.
In fact, function extensionality follows from the existence of
quotients, which we describe in the next section. In the Lean standard
library, therefore, funext is thus
proved from the quotient construction.
Suppose that for α:Typeu we define the Setα:=α→Prop to
denote the type of subsets of α, essentially identifying subsets
with predicates. By combining funext and propext, we obtain an
extensional theory of such sets:
defempty:Setα:=fun_=>Falsenotation(priority:=high)"∅"=>emptydefinter(ab:Setα):Setα:=funx=>x∈a∧x∈binfix:70" ∩ "=>intertheoreminter_self(a:Setα):a∩a=a:=setextfunVariable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x=>Iff.intro(fun⟨h,_⟩=>h)(funh=>⟨h,h⟩)theoreminter_empty(a:Setα):a∩∅=∅:=setextfun_=>Iff.intro(fun⟨_,h⟩=>h)(funh=>False.elimh)theoremempty_inter(a:Setα):∅∩a=∅:=setextfun_=>Iff.intro(fun⟨h,_⟩=>h)(funh=>False.elimh)theoreminter.comm(ab:Setα):a∩b=b∩a:=setextfun_=>Iff.intro(fun⟨h₁,h₂⟩=>⟨h₂,h₁⟩)(fun⟨h₁,h₂⟩=>⟨h₂,h₁⟩)
endSet
The following is an example of how function extensionality blocks
computation inside the Lean kernel:
deff(x:Nat):=xdefg(x:Nat):=0+xtheoremf_eq_g:f=g:=funextfunx=>(Nat.zero_addx).symmdefval:Nat:=Eq.recOn(motive:=fun__=>Nat)f_eq_g0-- does not reduce to 0f_eq_g▸0#reduceval
First, we show that the two functions f and g are equal using
function extensionality, and then we cast 0 of type Nat by
replacing f by g in the type. Of course, the cast is
vacuous, because Nat does not depend on f. But that is enough
to do the damage: under the computational rules of the system, we now
have a closed term of Nat that does not reduce to a numeral. In this
case, we may be tempted to reduce the expression to 0. But in
nontrivial examples, eliminating cast changes the type of the term,
which might make an ambient expression type incorrect. The virtual
machine, however, has no trouble evaluating the expression to
0. Here is a similarly contrived example that shows how
propext can get in the way:
Current research programs, including work on observational type
theory and cubical type theory, aim to extend type theory in ways
that permit reductions for casts involving function extensionality,
quotients, and more. But the solutions are not so clear-cut, and the
rules of Lean's underlying calculus do not sanction such reductions.
In a sense, however, a cast does not change the meaning of an
expression. Rather, it is a mechanism to reason about the expression's
type. Given an appropriate semantics, it then makes sense to reduce
terms in ways that preserve their meaning, ignoring the intermediate
bookkeeping needed to make the reductions type-correct. In that case,
adding new axioms in Prop does not matter; by proof irrelevance,
an expression in Prop carries no information, and can be safely
ignored by the reduction procedures.
Let α be any type, and let r be an equivalence relation on
α. It is mathematically common to form the “quotient” α/r,
that is, the type of elements of α “modulo” r. Set
theoretically, one can view α/r as the set of equivalence
classes of α modulo r. If f : α→β is any function that
respects the equivalence relation in the sense that for every
xy : α, rxy implies fx=fy, then f “lifts” to a function
f':α/r→β defined on each equivalence class ⟦x⟧ by
f'⟦x⟧=fx. Lean's standard library extends the Calculus of
Constructions with additional constants that perform exactly these
constructions, and installs this last equation as a definitional
reduction rule.
In its most basic form, the quotient construction does not even
require r to be an equivalence relation. The following constants
are built into Lean:
The first one forms a type Quotr given a type α by any binary
relation r on α. The second maps α to Quot α, so that
if r : α→α→Prop and a : α, then Quot.mkra is an
element of Quotr. The third principle, Quot.ind, says that
every element of Quot.mkra is of this form. As for
Quot.lift, given a function f : α→β, if h is a proof
that f respects the relation r, then Quot.liftfh is the
corresponding function on Quotr. The idea is that for each
element a in α, the function Quot.liftfh maps
Quot.mkra (the r-class containing a) to fa, wherein h
shows that this function is well defined. In fact, the computation
principle is declared as a reduction rule, as the proof below makes
clear.
The four constants, Quot, Quot.mk, Quot.ind, and
Quot.lift in and of themselves are not very strong. You can check
that the Quot.ind is satisfied if we take Quotr to be simply
α, and take Quot.lift to be the identity function (ignoring
h). For that reason, these four constants are not viewed as
additional axioms.
They are, like inductively defined types and the associated
constructors and recursors, viewed as part of the logical framework.
What makes the Quot construction into a bona fide quotient is the
following additional axiom:
This is the axiom that asserts that any two elements of α that are
related by r become identified in the quotient. If a theorem or
definition makes use of Quot.sound, it will show up in the
#print axioms command.
Of course, the quotient construction is most commonly used in
situations when r is an equivalence relation. Given r as
above, if we define r' according to the rule r'ab iff
Quot.mkra=Quot.mkrb, then it's clear that r' is an
equivalence relation. Indeed, r' is the kernel of the function
funa=>Quot.mkra. The axiom Quot.sound says that rab
implies r'ab. Using Quot.lift and Quot.ind, we can show
that r' is the smallest equivalence relation containing r, in
the sense that if r'' is any equivalence relation containing
r, then r'ab implies r''ab. In particular, if r
was an equivalence relation to start with, then for all a and
b we have rab iff r'ab.
To support this common use case, the standard library defines the
notion of a setoid, which is simply a type with an associated
equivalence relation:
The constants Quotient.mk, Quotient.ind, Quotient.lift,
and Quotient.sound are nothing more than the specializations of
the corresponding elements of Quot. The fact that type class
inference can find the setoid associated to a type α brings a
number of benefits. First, we can use the notation a≈b (entered
with \approx) for Setoid.rab, where the instance of
Setoid is implicit in the notation Setoid.r. We can use the
generic theorems Setoid.refl, Setoid.symm, Setoid.trans to
reason about the relation. Specifically with quotients we can use the
theorem Quotient.exact:
Together with Quotient.sound, this implies that the elements of
the quotient correspond exactly to the equivalence classes of elements
in α.
Recall that in the standard library, α×β represents the
Cartesian product of the types α and β. To illustrate the use
of quotients, let us define the type of unordered pairs of elements
of a type α as a quotient of the type α×α. First, we define
the relevant equivalence relation:
The next step is to prove that eqv is in fact an equivalence
relation, which is to say, it is reflexive, symmetric and
transitive. We can prove these three facts in a convenient and
readable way by using dependent pattern matching to perform
case-analysis and break the hypotheses into pieces that are then
reassembled to produce the conclusion.
Notice that we locally define the notation {a₁,a₂} for unordered
pairs as Quotient.mk'(a₁,a₂). This is useful for illustrative
purposes, but it is not a good idea in general, since the notation
will shadow other uses of curly brackets, such as for records and
sets.
We can easily prove that {a₁,a₂}={a₂,a₁} using Quot.sound,
since we have (a₁,a₂)~(a₂,a₁).
To complete the example, given a:α and u:UProdα, we
define the proposition a ∈ u which should hold if a is one of
the elements of the unordered pair u. First, we define a similar
proposition mem_fnau on (ordered) pairs; then we show that
mem_fn respects the equivalence relation eqv with the lemma
mem_respects. This is an idiom that is used extensively in the
Lean standard library.
For convenience, the standard library also defines Quotient.lift₂
for lifting binary functions, and Quotient.ind₂ for induction on
two variables.
We close this section with some hints as to why the quotient
construction implies function extensionality. It is not hard to show
that extensional equality on the (x:α)→βx is an equivalence
relation, and so we can consider the type extfunαβ of functions
“up to equivalence.” Of course, application respects that equivalence
in the sense that if f₁ is equivalent to f₂, then f₁a is
equal to f₂a. Thus application gives rise to a function
extfun_app:extfunαβ→(x:α)→βx. But for every f,
extfun_app(.mk_f) is definitionally equal to funx=>fx, which is
in turn definitionally equal to f. So, when f₁ and f₂ are
extensionally equal, we have the following chain of equalities:
Because Nonemptyα has type Prop and its constructor contains data, it can only eliminate to Prop.
In fact, Nonemptyα is equivalent to ∃x:α,True:
example(α:Typeu):Nonemptyα↔∃Variable name `x` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_xNote: This linter can be disabled with `set_option linter.unusedVariables false`x:α,True:=Iff.intro(fun⟨a⟩=>⟨a,trivial⟩)(fun⟨a,Variable name `h` is not explicitly referenced.Hint: The binding can be removed (if unused) or named `_` (if used implicitly). Alternatively, prefix the name with `_` to silence this warning:[apply]_hNote: This linter can be disabled with `set_option linter.unusedVariables false`h⟩=>⟨a⟩)
Our axiom of choice is now expressed simply as follows:
Given only the assertion h that α is nonempty, choiceh
magically produces an element of α. Of course, this blocks any
meaningful computation: by the interpretation of Prop, h
contains no information at all as to how to find such an element.
This is found in the Classical namespace, so the full name of the
theorem is Classical.choice. The choice principle is equivalent to
the principle of indefinite description, which can be expressed with
subtypes as follows:
Because it depends on choice, Lean cannot generate executable code for
indefiniteDescription, and so requires us to mark the definition
as noncomputable. Also in the Classical namespace, the
function choose and the property choose_spec decompose the two
parts of the output of indefiniteDescription:
Definition `inhabited_of_nonempty` of class type is semireducible. Most type class instances should be instance-reducible, so consider marking thisdefinition with `@[instance_reducible]`. If it is intentionally semireducible, this warning can be disabled with `set_option warn.classDefReducibility false`.noncomputabledefinhabited_of_nonempty(h:Nonemptyα):Inhabitedα:=choice(let⟨a⟩:=h;⟨⟨a⟩⟩)
In the next section, we will see that propext, funext, and
choice, taken together, imply the law of the excluded middle and
the decidability of all propositions. Using those, one can strengthen
the principle of indefinite description as follows:
Assuming the ambient type α is nonempty,
strongIndefiniteDescriptionp produces an element of α
satisfying p if there is one. The data component of this
definition is conventionally known as Hilbert's epsilon function:
Diaconescu's theorem states
that the axiom of choice is sufficient to derive the law of excluded
middle. More precisely, it shows that the law of the excluded middle
follows from Classical.choice, propext, and funext. We
sketch the proof that is found in the standard library.
First, we import the necessary axioms, and define two predicates U and V:
Each of U and V is a disjunction, so u_def and v_def
represent four cases. In one of these cases, u=True and
v=False, and in all the other cases, p is true. Thus we have:
havenot_uv_or_p:u≠v∨p:=bymatchu_def,v_defwith|Or.inrh,_=>p:PropU:Prop→Prop:=funx=>x=True∨pV:Prop→Prop:=funx=>x=False∨pexU:∃x,UxexV:∃x,Vxu:Prop:=chooseexUv:Prop:=chooseexVu_def:Uuv_def:Vvh:px✝:Vv⊢ u≠v∨pexactOr.inrhAll goals completed! 🐙|_,Or.inrh=>p:PropU:Prop→Prop:=funx=>x=True∨pV:Prop→Prop:=funx=>x=False∨pexU:∃x,UxexV:∃x,Vxu:Prop:=chooseexUv:Prop:=chooseexVu_def:Uuv_def:Vvx✝:Uuh:p⊢ u≠v∨pexactOr.inrhAll goals completed! 🐙|Or.inlhut,Or.inlhvf=>p:PropU:Prop→Prop:=funx=>x=True∨pV:Prop→Prop:=funx=>x=False∨pexU:∃x,UxexV:∃x,Vxu:Prop:=chooseexUv:Prop:=chooseexVu_def:Uuv_def:Vvhut:u=Truehvf:v=False⊢ u≠v∨papplyOr.inlp:PropU:Prop→Prop:=funx=>x=True∨pV:Prop→Prop:=funx=>x=False∨pexU:∃x,UxexV:∃x,Vxu:Prop:=chooseexUv:Prop:=chooseexVu_def:Uuv_def:Vvhut:u=Truehvf:v=False⊢ u≠vsimp[hvf,hut,This simp argument is unused:true_ne_falseHint: Omit it from the simp argument list.[apply]simp [hvf, hut]Note: This linter can be disabled with `set_option linter.unusedSimpArgs false`true_ne_false]p:PropU:Prop→Prop:=funx=>x=True∨pV:Prop→Prop:=funx=>x=False∨pexU:∃x,UxexV:∃x,Vxu:Prop:=chooseexUv:Prop:=chooseexVu_def:Uuv_def:Vvnot_uv_or_p:u≠v∨p⊢ p∨¬p
On the other hand, if p is true, then, by function extensionality
and propositional extensionality, U and V are equal. By the
definition of u and v, this implies that they are equal as well.
Consequences of excluded middle include double-negation elimination,
proof by cases, and proof by contradiction, all of which are described
in the section on classical logic.
The law of the excluded middle and propositional extensionality imply propositional completeness:
Together with choice, we also get the stronger principle that every
proposition is decidable. Recall that the class of Decidable
propositions is defined as follows:
In contrast to p∨¬p, which can only eliminate to Prop, the
type Decidablep is equivalent to the sum type Sum p (¬ p), which
can eliminate to any type. It is this data that is needed to write an
if-then-else expression.
As an example of classical reasoning, we use choose to show that if
f : α→β is injective and α is inhabited, then f has a
left inverse. To define the left inverse linv, we use a dependent
if-then-else expression. Recall that ifh:cthentelsee is
notation for ditec(funh:c=>t)(funh:¬c=>e). In the definition
of linv, choice is used twice: first, to show that
(∃a:α,fa=b) is “decidable,” and then to choose an a such that
fa=b. Notice that propDecidable is a scoped instance and is activated
by the openClassical command. We use this instance to justify
the if-then-else expression. (See also the discussion in
Decidable Propositions).
openClassicalDefinition `linv` is a proposition; use `theorem` instead of `def`Note: This linter can be disabled with `set_option linter.defProp false`noncomputabledeflinv[Inhabitedα](f:α→β):β→α:=funb:β=>ifex:(∃a:α,fa=b)thenchooseexelsedefaulttheoremlinv_comp_self{f:α→β}[Inhabitedα](inj:∀{ab},fa=fb→a=b):linvf∘f=id:=funextfuna=>haveex:∃a₁:α,fa₁=fa:=⟨a,rfl⟩havefeq:f(chooseex)=fa:=choose_specexcalclinvf(fa)_=chooseex:=rfl_=a:=injfeq
From a classical point of view, linv is a function. From a
constructive point of view, it is unacceptable; because there is no
way to implement such a function in general, the construction is not
informative.