So far we have used Mathlib as a black box: write import Mathlib, then call ring, simp or exact? and hope. That works until it does not, and when it fails the error messages talk about things like “instances”, “↑n” and “Tendsto”. This lecture opens the box. It answers a handful of questions that every Mathlib user meets in the first week:

  • How does Lean know what * means on ?
  • Why does a lemma proved once for all commutative rings apply to , and , but not to matrices?
  • Why do arrows ↑ appear in your goals?
  • How are sums and limits written?
  • How can you guess the name of a lemma before you search for it?

None of this is new mathematics. It is the design of a very large library, and knowing it is what makes step 6 of Lecture 5’s recipe (search) fast. Lecture 7 relies on all of it.

Cheatsheet

Type classes: how a * b finds its meaning

When you write a * b with a b : ℝ, Lean must find a multiplication on . It does this with type classes (Definition 6.1).

Definition 6.1 (Type class and instance).

A type class is a structure that Lean fills in automatically, such as Mul α, “a multiplication on α”, or Field K, “a field structure on K”. An instance is a registered value of a class for a particular type, such as the field structure on . An argument in square brackets, as in [Field K], asks Lean to find the instance by itself. This search is called instance resolution.

The command #synth runs the search and shows what it found:

import Mathlib
 
#synth Mul ℝ
#synth Field ℝ

Lean answers Real.instMul and Real.instField: the names of the instances that Mathlib registered when it constructed the reals. To see the mechanism with nothing hidden, here is a small class of our own: a type with an associative operation and a two-sided identity.

class MyMonoid (α : Type) where
  op : α → α → α
  e : α
  op_assoc : ∀ a b c, op (op a b) c = op a (op b c)
  e_op : ∀ a, op e a = a
  op_e : ∀ a, op a e = a
 
instance : MyMonoid ℕ where
  op := (· + ·)
  e := 0
  op_assoc := Nat.add_assoc
  e_op := Nat.zero_add
  op_e := Nat.add_zero
 
theorem MyMonoid.e_unique {α : Type} [MyMonoid α] (e' : α)
    (h : ∀ a, MyMonoid.op e' a = a) : e' = MyMonoid.e :=
  calc e' = MyMonoid.op e' MyMonoid.e := (MyMonoid.op_e e').symm
    _ = MyMonoid.e := h _
 
#eval (MyMonoid.op 2 3 : ℕ)

The class bundles operations and the laws they satisfy, so an instance is a proof as well as a definition. The theorem MyMonoid.e_unique (identities are unique) is proved once, for every type with an instance. At ℕ Lean finds the instance above, and #eval prints 5, because op is addition there. Mathlib’s Monoid, Ring and Field are the same idea, with more fields and a careful design.

When the search fails, Lean says so. The message failed to synthesize has two common causes. Either the structure really does not exist, or you are working in a different type from the one you think:

#synth Field ℤ
#check (-1 : ℕ)

The first reports failed to synthesize Field ℤ, which is correct: is not a field. The second reports that Lean failed to synthesize Neg ℕ. The natural numbers have no negation, so -1 cannot be a natural number. The fix is to say which type you mean, as in (-1 : ℤ). Many puzzling errors in early proofs are this one: a numeral that Lean elaborated in ℕ because nothing told it otherwise.

Type classes also explain the decide tactic from earlier lectures. Decidable p is a class, and an instance of it is an algorithm that answers the question p. Instance resolution picks one for you:

#synth Decidable ((3 : ℕ) = 4)
#synth Decidable ((3 : ℝ) = 4)

For ℕ Lean finds instDecidableEqNat, a genuine algorithm, so decide can run it. For ℝ it finds Real.decidableEq, which Mathlib declares noncomputable: the instance exists by classical logic, but there is no algorithm inside it to run. Lecture 7 meets this when it asks decide to multiply complex matrices.

The hierarchy: extends, and bundled maps

Mathlib does not define a field from scratch. It says that a field is a commutative ring that is also a division ring. In the source (Mathlib/Algebra/Field/Defs.lean) the line reads class Field (K : Type u) extends CommRing K, DivisionRing K. Each extends creates a function from the larger structure to the smaller one. That function is itself an instance, so from [Field K] Lean can find CommRing K, then Ring K, then Monoid K, and so on up the chain. The figure shows a slice of this hierarchy; each arrow is one extends.

arrow A to B: A extends B Monoid DivInvMonoid MonoidWithZero CommMonoid Semiring AddCommGroup Ring DivisionRing CommRing Field ℚ ℝ ℂ instances

Every arrow in the figure is a function you can #check. Each line below prints a type such as @Field.toCommRing : {K : Type u_1} → [self : Field K] → CommRing K, which reads “given a field structure on K, here is a commutative ring structure”.

#check @Field.toCommRing
#check @Field.toDivisionRing
#check @DivisionRing.toRing
#check @DivisionRing.toDivInvMonoid
#check @CommRing.toRing
#check @CommRing.toCommMonoid
#check @Ring.toSemiring
#check @Ring.toAddCommGroup
#check @Semiring.toMonoidWithZero
#check @MonoidWithZero.toMonoid
#check @CommMonoid.toMonoid
#check @DivInvMonoid.toMonoid

A field reaches Monoid by three paths in the figure: through CommMonoid, through DivInvMonoid, and through Semiring. Such a diamond would be a problem if the paths gave two different multiplications. They do not, because extends makes the structures share their fields, and Lean confirms it by unfolding definitions:

example (K : Type) [Field K] :
    (CommRing.toCommMonoid : CommMonoid K).toMonoid =
      (DivisionRing.toDivInvMonoid : DivInvMonoid K).toMonoid := rfl

Mathlib’s classes are designed so that diamonds like this one commute in this strong sense, by rfl. When one does not, proofs fail in confusing ways, so the design takes care.

The payoff is reuse. A theorem stated for every commutative ring applies, with no extra work, to each type that has a CommRing instance, directly or through Field:

theorem sq_add {R : Type*} [CommRing R] (a b : R) :
    (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by ring
 
example (x y : ℝ) : (x + y) ^ 2 = x ^ 2 + 2 * x * y + y ^ 2 := sq_add x y
example (x y : ZMod 5) : (x + y) ^ 2 = x ^ 2 + 2 * x * y + y ^ 2 := sq_add x y

Square matrices are the instructive failure. They form a ring, and #synth Ring finds Matrix.instRing, but they are not commutative. So applying sq_add to two matrices fails:

example (A B : Matrix (Fin 2) (Fin 2) ℝ) :
    (A + B) ^ 2 = A ^ 2 + 2 * A * B + B ^ 2 := sq_add A B

Lean reports that it failed to synthesize CommRing (Matrix (Fin 2) (Fin 2) ℝ). The error is mathematically correct: for matrices , and in general. Lecture 7’s Pauli matrices, with , are an example.

Bundled maps. Structure-preserving maps are organised the same way. A ring homomorphism f : R →+* S is not a bare function: it is a structure holding the function together with proofs that it preserves , , and (Definition 6.2).

Definition 6.2 (Bundled morphism).

A bundled morphism is a structure that packs a function with the proofs of its properties. The main kinds are M →* N (monoid homomorphisms), R →+* S (ring homomorphisms) and V →ₗ[R] W (R-linear maps). A bundled map can be applied like a function, and lemmas such as map_mul and map_add work for every kind at once.

#check Nat.castRingHom ℝ
#check Complex.ofRealHom
#check starRingEnd ℂ
 
example (z w : ℂ) :
    starRingEnd ℂ (z * w) = starRingEnd ℂ z * starRingEnd ℂ w :=
  map_mul _ z w

The three #checks print ℕ →+* ℝ, ℝ →+* ℂ and ℂ →+* ℂ: the inclusion of in , the inclusion of in , and complex conjugation. The last is the star of Lecture 7’s brackets. Linear maps follow the same pattern: Matrix.mulVecLin M is the matrix M seen as a linear map (n → R) →ₗ[R] (m → R).

Coercions: from ℕ to ℤ to ℝ

Mathematicians treat as inclusions and never think about them. In Lean these are three different types, and moving a number from one to another is a function, the cast. Lean inserts it automatically and prints it as ↑:

#check ((3 : ℕ) : ℝ)

The answer is ↑3 : ℝ, “the natural number 3, cast to a real”. Most of the time the arrow is harmless. It matters when an operation behaves differently in the two types. Natural-number subtraction stops at zero, so the place where the cast happens changes the answer:

example : ((5 - 7 : ℕ) : ℤ) = 0 := by norm_num
example : ((5 : ℕ) : ℤ) - 7 = -2 := by norm_num

In the first line the subtraction happens in ℕ, giving 0, and the result is cast. In the second the cast happens first, and the subtraction is in ℤ. Mathlib has tactics to move casts around:

  • push_cast pushes ↑ inward, towards the variables, using lemmas such as ↑(m + n) = ↑m + ↑n.
  • norm_cast and exact_mod_cast go the other way. They show that a statement about casts follows from the same statement without them.
example (n : ℕ) : ((n + 1 : ℕ) : ℝ) = (n : ℝ) + 1 := by
  push_cast
  ring
 
example (m n : ℕ) (h : (m : ℝ) < n) : m < n := by
  exact_mod_cast h

The rule of thumb: when a goal has ↑ in awkward places, try push_cast first. If the goal is the hypothesis with casts added, try exact_mod_cast.

Finite sums, and a first look at matrices

A finite set in Mathlib is a Finset α: a list with no repeated elements, up to order. Finset.range n is . The big-operator notation ∑ i ∈ s, f i stands for Finset.sum s f, and ∏ works the same way. Small sums over ℕ can be computed: decide proves the line below, and #eval prints 10.

example : ∑ i ∈ Finset.range 5, i = 10 := by decide
 
#eval ∑ i ∈ Finset.range 5, i

For a general n you need induction and one key lemma, Finset.sum_range_succ. It splits off the last term:

#check @Finset.sum_range_succ

It prints ∑ x ∈ Finset.range (n + 1), f x = ∑ x ∈ Finset.range n, f x + f n, valid in any AddCommMonoid. With it, Gauss’s formula takes four lines:

theorem gauss (n : ℕ) :
    2 * ∑ i ∈ Finset.range (n + 1), i = n * (n + 1) := by
  induction n with
  | zero => simp
  | succ k ih =>
    rw [Finset.sum_range_succ, mul_add, ih]
    ring

The statement multiplies by 2 to avoid dividing in ℕ, where / rounds down. That is a junk value from Lecture 5, sidestepped by choosing the statement. In the successor step, sum_range_succ peels off the term , mul_add distributes the 2, the induction hypothesis ih replaces the old sum, and ring finishes the algebra.

Sums are also how Mathlib builds linear algebra. A matrix Matrix m n R is just a function m → n → R, and the product is defined entry by entry as a sum: the lemma Matrix.mul_apply says (M * N) i k = ∑ j, M i j * N j k. The inner product on EuclideanSpace ℂ n is the sum . Lecture 7 uses both, with n = Fin 2 for one qubit.

Limits as filters, and how lemmas are named

Analysis has many kinds of limit: as , as , one-sided limits, limits at . Mathlib handles them all with one definition, using filters (Definition 6.3).

Definition 6.3 (Filter and Tendsto).

A filter on α is a collection of subsets of α that is closed under taking supersets and finite intersections. Think of it as “the sets that contain all points close enough to somewhere”. atTop : Filter ℕ contains each set that includes every for some . 𝓝 a contains each neighbourhood of . Tendsto f F G says that the preimage under f of every set in G is in F.

With F = atTop and G = 𝓝 a, unfolding Tendsto gives “for every neighbourhood of , for all large ”, which is the usual sequence limit. With F = 𝓝 c it is a limit at a point. One set of lemmas about Tendsto covers every case at once. Here is a sequence limit, found by search:

open Filter Topology
 
example : Tendsto (fun n : ℕ => (1 : ℝ) / (n + 1)) atTop (𝓝 0) := by
  exact tendsto_one_div_add_atTop_nhds_zero_nat

exact? on this goal prints Try this: and then [apply] exact tendsto_one_div_add_atTop_nhds_zero_nat. The name is long, but you could have guessed most of it. Mathlib names a lemma by reading its conclusion from left to right (naming conventions):

piece of the namewhat it describes
tendstothe conclusion is a Tendsto
one_div_addthe function is 1 / (· + ·)
atTopthe source filter
nhds_zerothe target filter 𝓝 0 (𝓝 is spelled nhds)
natthe variable is a natural number

The same convention gives mul_comm (a * b = b * a), add_le_add (add two inequalities) and sum_range_succ. Hypotheses come after _of_, so le_of_lt turns a < b into a ≤ b. Equivalences contain _iff_. Once you know the convention, a guess plus exact?, or a pattern search in Loogle, usually finds a lemma in seconds. Lecture 5 covers the search tools. The rule worth remembering is that Mathlib names describe statements, not proof ideas or the people who found them. A few famous results, such as ZMod.wilsons_lemma, are the exceptions.

Continuity is a limit too. The lemma Continuous.tendsto turns a proof that a function is continuous into a Tendsto at every point:

example (x : ℝ) : Tendsto (fun y : ℝ => y ^ 2) (𝓝 x) (𝓝 (x ^ 2)) :=
  (continuous_pow 2).tendsto x

Try this

  • Run #synth on Field (ZMod 3), Field (ZMod 4) and Field (ZMod 5). Two of them fail, for different reasons: one is mathematical, and the other is that Mathlib has not been told that 5 is prime. Add instance : Fact (Nat.Prime 5) := ⟨by norm_num⟩ and try again.
  • Prove over ℕ with the same pattern as gauss.
  • Use push_cast to prove ((n * (n + 1) : ℕ) : ℝ) = (n : ℝ) * (n + 1).
  • Guess the name of the lemma that says , then ask exact?. Compare its answer with your guess: which side does left or right refer to?

Readings