About this notebook

Companion to Lecture 0: Orientation. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)

Every notebook in this course mixes two languages. The grey cells that start with %%lean contain Lean code, and Lean checks them. The other code cells are Python, used for small experiments and pictures. In this notebook you will:

  1. see how a %%lean cell reaches Lean and how the answer comes back;
  2. run a first #eval and #check;
  3. prove a first theorem, once as a term and once with a tactic;
  4. read an error message, and see what an unfinished proof (sorry) reports.

0. How a %%lean cell runs

The notebook itself runs Python. A small Python package, leanmagic, starts one Lean process when the notebook opens and keeps it running. That process is the Lean REPL (read-eval-print loop), a program that takes Lean code as JSON on its input and answers with Lean’s messages as JSON.

  notebook cell              Python kernel                Lean process
 +---------------+  code   +-----------------+  JSON   +----------------------+
 | %%lean        | ------> | leanmagic       | ------> | lake exe repl        |
 | theorem ...   |         |  - which env?   |  stdin  |  elaborator + kernel |
 +---------------+         |  - memory guard |         |  env 0, env 1, ...   |
 +---------------+  box    |  - draw result  |  JSON   |                      |
 | coloured box  | <------ |                 | <------ |  messages, goals     |
 +---------------+         +-----------------+ stdout  +----------------------+

Each cell that Lean accepts produces a new environment: everything declared so far, identified by a number. The next cell runs on top of it, so the cells share one growing environment, just like the lines of one Lean file. Two options change where a cell starts and whether later cells see it:

  header --> env A --cell 1--> env B --cell 2--> env C --cell 3--> ...
               |                        |
               |                        +-- %%lean --expect-error: runs on env C,
               |                            but the next cell still starts from env C
               +-- %%lean --fresh: runs on the header alone, forgetting cells 1 to 3

The coloured box under a cell is Lean’s answer. Green means accepted. Gold means accepted with a sorry, an unfinished proof. A box marked “rejected, as intended” belongs to a cell with --expect-error: a counterexample that is meant to fail. Anything else in red is a real failure.

The first code cell starts Lean and elaborates the notebook’s header, the lines that would sit at the top of a Lean file. Here the header is empty: plain Lean, no Mathlib, so Lean starts in a few seconds.

import leanmagic
 
leanmagic.setup("")
Lean 4.35.0 ready; header `(empty header)` elaborated.

1. Ask Lean something

#eval runs an expression and prints its value. #check prints the expression with its type, without running it. In VS Code the same output appears in the infoview, the panel beside your file.

#eval 2 + 3 * 4
#eval "Hello, " ++ "Lean"
#check 2 + 3 * 4
#check "Hello"

✓ Lean accepted this

14
"Hello, Lean"
2 + 3 * 4 : Nat
"Hello" : String

A definition made in one cell is available in every later cell:

def square (n : Nat) : Nat := n * n

✓ Lean accepted this (no messages)

#eval square 12
#eval (List.range 6).map square
#print square

✓ Lean accepted this

144
[0, 1, 4, 9, 16, 25]
def square : Nat → Nat :=
fun n ↦ n * n

#print shows the definition as Lean stored it. fun n ↦ n * n is the function that sends n to n * n; def square (n : Nat) was shorthand for it.

2. A first theorem, two ways

A theorem is a name, a statement, and a proof. The statement is written after the colon, and the proof after :=. The simplest proofs are terms. Here the term is rfl, short for “reflexivity”: both sides compute to the same value, so they are equal.

theorem square_three : square 3 = 9 := rfl
 
theorem square_eq (n : Nat) : square n = n * n := rfl

✓ Lean accepted this (no messages)

The second theorem is about every n, not one number: Lean unfolds square n to n * n without knowing what n is. Lecture 2 explains exactly which computations rfl may use.

A proof can also be a tactic script: after by, a list of commands that build the proof term for you. decide evaluates a yes/no question, and omega proves linear arithmetic facts about whole numbers.

theorem square_three' : square 3 = 9 := by
  decide
 
theorem two_mul_term (n : Nat) : 2 * n = n + n := Nat.two_mul n
 
theorem two_mul_tactic (n : Nat) : 2 * n = n + n := by
  omega

✓ Lean accepted this (no messages)

two_mul_term reuses a theorem from Lean’s library, Nat.two_mul. Whatever the script, the result is a term, and #print shows it. The tactic decide wrote a term that asks the kernel to evaluate the question to true:

#print two_mul_term
#print square_three'

✓ Lean accepted this

theorem two_mul_term : ∀ (n : Nat), 2 * n = n + n :=
fun n ↦ Nat.two_mul n
theorem square_three' : square 3 = 9 :=
of_decide_eq_true (id (Eq.refl true))

3. Reading an error

Errors are the main way Lean talks to you, so it pays to read them slowly. This cell is marked --expect-error: the claim is false, and the cell shows what Lean says about it.

This cell is meant to fail:

theorem square_three_wrong : square 3 = 10 := by
  decide

✗ rejected, as intended

error, line 2Tactic `decide` proved that the proposition
  square 3 = 10
is false

The message has two parts. The position says which line of the cell Lean is complaining about: line 2, where decide ran. The text says what went wrong: decide computed the answer and found the statement false. A false statement has no proof, so no tactic can help.

Typos produce the most common error of all. Lean does not guess what you meant: an unknown name is an error. (In this course the option autoImplicit is off, so Lean never silently turns an unknown name in a statement into a new variable.)

This cell is meant to fail:

#eval squre 12

✗ rejected, as intended

error, line 1Unknown identifier `squre`

Because both cells above were marked --expect-error, nothing from them reaches later cells. In a Lean file it is different: after an error, Lean still records the theorem, with the broken part of the proof replaced by sorry, so that later lines can be checked. Here, the failed theorem is simply not there:

This cell is meant to fail:

#check square_three_wrong

✗ rejected, as intended

error, line 1Unknown identifier `square_three_wrong`

A --fresh cell starts again from the header alone. It does not see square, which is why this cell fails. Since it is also --expect-error, later cells still see everything defined above.

This cell is meant to fail:

#eval square 12

✗ rejected, as intended

error, line 1Unknown identifier `square`

4. What sorry reports

sorry stands in for a proof you have not written yet. Lean accepts the theorem with a warning, and the gold box shows the goal that sorry is hiding: the hypotheses above the turnstile ⊢, and the statement still to prove below it. This is what the infoview shows while you write a proof.

theorem square_pos (n : Nat) (h : 0 < n) : 0 < square n := by
  sorry

◐ accepted with sorry: goals left open

goal at line 2n : Nat
h : 0 < n
⊢ 0 < square n

A sorry never disappears silently. #print axioms lists everything a theorem rests on, and a proof with a hole rests on sorryAx:

#print axioms square_pos

✓ Lean accepted this

'square_pos' depends on axioms: [sorryAx]

Here is the finished proof. unfold square replaces square n by its definition, which leaves 0 < n * n; the library fact Nat.mul_pos says a product of two positive numbers is positive.

theorem square_pos' (n : Nat) (h : 0 < n) : 0 < square n := by
  unfold square
  exact Nat.mul_pos h h
 
#print axioms square_pos'

✓ Lean accepted this

'square_pos'' does not depend on any axioms

5. Lean from Python

The same session can be used from Python. leanmagic.lean(code) runs Lean code and returns its messages as data. Here Python asks Lean for a few values of square and compares them with its own arithmetic. advance=False keeps these checks out of the environment, and show_output=False skips the coloured box.

for n in [0, 1, 7, 12, 1000]:
    r = leanmagic.lean(f"#eval square {n}", advance=False, show_output=False)
    lean_says = r.infos[0].data.strip()
    print(f"square {n:>4} = {lean_says:>7}   Python agrees: {int(lean_says) == n * n}")
square    0 =       0   Python agrees: True
square    1 =       1   Python agrees: True
square    7 =      49   Python agrees: True
square   12 =     144   Python agrees: True
square 1000 = 1000000   Python agrees: True

When Lean gets stuck

Every cell has a time limit, and Lean is stopped if it uses more than 16 GB of memory. After either, or if the session seems confused, run %lean_restart in a code cell to start a new Lean process. %lean_reset keeps the process but forgets every cell since the header. Both mean re-running the cells you still need.

Try this

  • Define cube (n : Nat) : Nat, check cube 3 = 27 with rfl and with decide, and #print both proofs.
  • Change square_three to claim square 3 = 10 without --expect-error. What does the box say, and what colour is it?
  • Prove theorem square_mono (a b : Nat) (h : a ≤ b) : square a ≤ square b by starting with sorry, reading the goal, and then trying unfold square followed by exact Nat.mul_le_mul h h.
  • Run #check Nat.two_mul and #check @Nat.mul_pos. What does the @ change?