8. Programming in Lean

Draft

The logic is a programming language

Sections 5 and 6 presented Lean's calculus as a foundation for mathematics. That same calculus is also a functional programming language with inductive data types, pattern matching, and a compiler, and Lean 4 is largely written in itself: the elaborator of Section 9 (which translates source syntax into kernel terms), the tactics of Section 10, and the build tool are all Lean programs. Three features of that language matter directly to anyone reading a formal proof. First, every computable definition can be run by two separate evaluators: the kernel, which reduces symbolic terms by the rules of Section 6.3, and the compiler, which executes compiled code; only what the kernel reduces counts inside a proof. Second, programs with mutable state or failure are encoded as pure, total functions behind surface notation, so the logic can state theorems about them. Third, every tactic is such a program: it inspects an open goal, writes a term, and hands the finished result to the kernel to verify. Nobody writes raw kernel terms by hand; Lean's programming language is what writes them.

Understanding how programs construct proof terms is the third of the series' five steps: a proof is a term (Sections 1 to 4) in one core language checked by a small kernel (Sections 5 to 7), and programs write that term. Each topic here builds on the one before it. Because a recursive definition defines a valid mathematical function only when its recursion terminates, the elaborator translates recursion into primitive recursors or termination proofs that the kernel checks and the compiler never sees; Sections 8.2 and 8.3 examine how the two evaluators diverge. Overloading operators and sequencing stateful or fallible actions across different types then rely on type classes (Section 8.4) and monads (Section 8.5), which supply the goal-list state and error handling that tactics run on (Section 8.6).

Addition of natural numbers, as Lean's core library defines it, shows the first of the three in a few lines.

/--
Addition of natural numbers, typically used via the `+` operator.

This function is overridden in both the kernel and the compiler to efficiently evaluate using the
arbitrary-precision arithmetic library. The definition provided here is the logical model.
-/
-- ...
@[extern "lean_nat_add", instance_reducible]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
  | a, Nat.zero   => a
  | a, Nat.succ b => Nat.succ (Nat.add a b)

The three equations of Nat.add are the mathematical definition: Nat has constructors zero and succ (Section 5.6), and addition branches on its second argument, making a single recursive call on the smaller subterm b inside Nat.succ b. Every annotation around those three lines addresses the two evaluators: the doc comment notes that both kernel and compiler override these equations with arbitrary-precision integer arithmetic while keeping the equations as the logical specification; extern names the C runtime function called by compiled code; and @& instructs the compiler to borrow the argument by reference without adjusting its reference count, a memory hint that the type system ignores.

Three properties let one definition serve both sides. The language is pure: the value of a function depends on its arguments alone, and computing it changes nothing; there is no assignment and no loop, only definitions, cases and recursion (the loops and assignments of do notation, Section 8.5, are notation for these). It is total: a function of type Nat → Nat returns a number for every number, and Lean refuses a recursion that it cannot show to end, which is the matter of Section 8.3. And its types are those of Section 5, so that Nat.add is at once a program and a term that a theorem can mention; its data are the inductive types of that section, among them structures, which are inductive types with one constructor.

The simplest reason for a recursion to end is the one in the definition of addition.

Definition 8.1.1 (structural recursion). A recursive definition of a function on an inductive type is structural if, for one of its arguments, every recursive call is made on a proper part of that argument: on a term that stands under at least one constructor in it, as b stands in Nat.succ b, or on a value of a function that stands there.

Because every value of an inductive type is assembled by finitely many constructors, stripping off at least one constructor at each recursive call guarantees termination and lets the elaborator compile the definition directly into the type's primitive recursor (Section 5.6).

Both evaluators can be asked at once. The command #eval hands an expression to the compiler and prints its value. The term rfl, the proof that a thing is equal to itself, is accepted for an equation when its two sides are definitionally equal, which the kernel decides by reducing them (Section 6.3).

#eval 2 + 3                   -- the compiler runs code and prints 5
example : 2 + 3 = 5 := rfl    -- the kernel reduces both sides and accepts

On 2 + 3 nobody could tell the two apart. Section 8.2 takes a function on which a clock can.

One definition, two evaluators

The natural guess is that the kernel is a slow copy of the compiler: the same program, run by rewriting terms. Proofs by computation are checked at the kernel's speed (Section 10.4), so the guess is worth a test. The Fibonacci function, written as a first course writes it, makes two recursive calls. Ask Lean for its values in three ways: with #eval, which compiles the definition and runs the code; with the kernel, which reduces the term it was given; and with the kernel once more, on a second definition that has the same three equations and one line more, termination_by n => n, which tells Lean to justify the recursion by a number that decreases and not by the shape of the argument.

chart    one function, defined twice (fibW adds the line termination_by n => n), run three ways:
         time against n, every recorded run a dot

                 n    #eval fib n    kernel, fib    kernel, fibW (green)
                20        5.60 ms        0.62 ms          445 ms
                24        28.8 ms        0.74 ms        3,952 ms
                28         190 ms        0.79 ms         32.3 s, 7.6 GB
                32       1,289 ms        0.86 ms         not run
                40         60.3 s
                44    stopped by the recording after 150 s
             1,024                       28.2 ms
           200,000                       10.1 s
         1,000,000                       (kernel) excessive memory consumption detected (12.6 GB given)

         clocks   #eval: the whole command (floor 1.6 ms); the kernel: the evaluation alone. Timed alike they are
                  within a tenth at n = 16 (0.55 and 0.59 ms); from n = 20 on the kernel on fib is the faster
         budget   the kernel's own, lowered from 200,000 to 100, is met by fib at n = 2,000: (kernel) deterministic timeout;
                  at the default, fibW would meet it near n = 32 (extrapolated from 3 counted points)
         depth    the elaborator answered at n = 128 and was refused at n = 256: maximum recursion depth has been reached

chart    Euclid's primality test, decide (Euclid.Prime p), same time scale: at p = 30,011 the kernel
         takes 35.0 s and native code 3.28 ms, 10,700 times less
(the live figure needs JavaScript and loads about 0.06 MB; [run] loads 0.9 MB more and runs a kernel in the page)
The naive Fibonacci function, defined twice and run by Lean 4.35.0: a recording, every run a dot, medians joined. Green: the kernel on the well-founded definition. Ink: #eval, timed as the whole command, and the kernel on the structural definition, timed around the evaluation alone; hairlines: the other evaluators. Crosses: runs stopped by Lean, with its message (one at the kernel's own budget, lowered), or by the recording, at the hatched limit. The second chart: the running example's primality test on the same time scale; rings: the kernel of this page on the same term, timed in your browser. Point at a dot, or press run.

Example 8.2.1 (the naive Fibonacci function, timed three ways). On a 16-core server shared with other jobs, Lean 4.35.0 ran the two definitions fib and fibW three times at each input, each run in a fresh process, quoting the median (across all three curves the slowest run at a point lies within 16% of the fastest); the kernel's clock timed the reduction alone, whereas #eval was timed as a whole command, which carries a 1.6 ms floor before computing anything.

#eval takes the time the equations ask for. Its curve follows the number of calls they make, 1,028,457 at \(n = 28\), which grows as the Fibonacci numbers themselves do: 190 ms there, and at \(n = 44\) the recording stopped it after 150 s. The kernel on fib does not follow the calls. Its time grows with \(n\), 0.79 ms at \(n = 28\) and 28.2 ms at \(n = 1{,}024\), where the value has 214 digits, and at \(n = 200{,}000\) it still answered, in 10.1 s for the last three digits. The kernel on fibW follows the calls again and pays far more for each: 32.3 s and 7.6 GB of memory at \(n = 28\), beyond which it was not run. With one clock for both, around the call alone, the kernel on fib is slower than the code that #eval runs at \(n = 12\), level with it at \(n = 16\) and faster from \(n = 20\) on. ◁

So the kernel is not a slow copy of the compiler, and the compiler is not a fast copy of the kernel. They were handed different programs. The reason lies in Section 6: the kernel knows recursors and nothing else that recurses, and Lean's reference says as much of the core theory (Section 9.7 quotes the passage). What a user writes therefore leaves the elaborator in two versions.

Definition 8.2.2 (the two programs of a definition). The pre-definition of a recursive definition is its body as a term of the core language, in which pattern matching has been replaced by auxiliary functions (Section 9.7) and the function being defined may still occur. The compiler is given the pre-definition. The kernel is given a term in which the function no longer occurs: the recursion has been replaced by a recursor (Definition 8.1.1), by a well-founded fixpoint (Theorem 8.3.2) or by a partial fixpoint. Of a definition marked partial the kernel is given an opaque constant, a name with a type and no body to unfold.

The names and the reasons for the split are the reference's.

The pre-definition is then sent to the compiler and to the kernel. The compiler receives the pre-definition as-is, with recursion intact. The version sent to the kernel, on the other hand, undergoes a second transformation that replaces explicit recursion with uses of recursors, well-founded recursion, or partial fixpoint recursion. This split is for three reasons: The compiler can compile partial functions that the kernel treats as opaque constants for the purposes of reasoning. The compiler can also compile unsafe functions that bypass the kernel entirely. Translation to recursors does not necessarily preserve the cost model expected by programmers, in particular laziness vs strictness, but compiled code must have predictable performance. The other strategies used to justify recursive definitions result in internal terms that are even further from the program as it was written.

—"The Lean Language Reference", edition for Lean 4.35.0. Section 2.4, "Elaboration Results" (lean-lang.org/doc/reference/4.35.0). The three reasons are a bulleted list on the page, run into the paragraph here. The sentence quoted before it opens the section, and the paragraph before this one names the pre-definition. Partial fixpoints, the third strategy it names, serve functions that need not terminate; this series does not use them.

The source of fib is four lines.

def fib : Nat → Nat
  | 0 => 0
  | 1 => 1
  | n + 2 => fib n + fib (n + 1)

What the kernel was handed for it, Lean prints on request, with #print fib and #print fib._f.

def fib : Nat → Nat :=
fun x => Nat.brecOn x fib._f
@[reducible] def fib._f : (x : Nat) → Nat.below x → Nat :=
fun x f =>
  (match (motive := (x : Nat) → Nat.below x → Nat) x with
    | 0 => fun x => 0
    | 1 => fun x => 1
    | n.succ.succ => fun x => x.2.1 + x.1)
    f

Why did the kernel run naive fib in milliseconds where #eval took minutes? Plain Nat.rec hands its step function only the value at the immediate predecessor, whereas fib (n + 2) needs both fib (n + 1) and fib n two steps down. To bridge that two-step lookback, the elaborator compiled structural fib through Nat.brecOn (course-of-values recursion, built atop Nat.rec of Section 5.6), which threads a nested tuple of type Nat.below x holding the values already computed at smaller numbers and hands that tuple to fib._f. In its n.succ.succ branch, fib._f makes no recursive calls of its own: it simply projects out two entries of the tuple (x.2.1 for fib n and x.1 for fib (n + 1)) and adds them. Translating two-step structural recursion into Nat.brecOn turned exponential tree recursion into the bottom-up dynamic-programming table a programmer would write by hand (how much of the kernel's curve comes from that tuple representation and how much from the kernel's sharing of already-reduced subterms, the recording does not separate). In fibW, by contrast, the termination_by clause bypassed Nat.brecOn and compiled the body to a well-founded fixpoint (Section 8.3) that branches into two genuine recursive calls at every step, each carrying a proof term that its argument decreased.

Where each curve ends says as much as where it runs. #eval was ended by the recording. The kernel on fib ended on memory: at \(n = 1{,}000{,}000\), with the 12.6 GB that the recording allowed it, Lean answered (kernel) excessive memory consumption detected. The elaborator has a reducer of its own, which rfl and decide ask before they ask the kernel, and it gives up far earlier: it still answered at \(n = 128\), and at \(n = 256\) it said maximum recursion depth has been reached.decide proves a proposition by evaluating a test for it, and +kernel leaves the evaluation to the kernel alone; the tactic is the subject of Section 10.4. No run of this recording at Lean's default settings met a limit of the kernel other than the memory given to Lean. The kernel does have a budget when a declaration is added the ordinary way: the option maxHeartbeats, 200,000 by default and counted in thousands of kernel steps, past which Lean says (kernel) deterministic timeout. With the budget lowered, the message can be had at once.

set_option maxHeartbeats 100 in
example : fib 2000 % 1000 = 125 := by decide +kernel
error: (kernel) deterministic timeout

Without its first line the example is accepted, as it is with a budget of 145 in place of 100. By an extrapolation from three counted points, fibW would spend the default budget near \(n = 32\).

On a function whose equations make a single recursive call to a step, the contrast is the expected one. The primality test of the series' running example, Euclid, is trial division written as a bounded search of that kind. At \(p = 30{,}011\) the kernel takes 35.0 s and the same test, compiled to a native binary, 3.28 ms, 10,700 times less (medians of three runs, both clocks read around the call alone; the three runs of each lie within 5% of one another). #eval lies between the two: as timed here it runs at the speed of Lean's interpreter of compiled code, which on fib is about a hundred times slower than the native binary.

The two evaluators agree on values by design, and that is all they share. What the kernel computes is definitional equality: rfl proves fib 20 = 6765 because the kernel reduces fib 20 to 6765, and that reduction is part of checking the proof. What the compiler computes is a line of output.

Remark 8.2.3 (what #eval establishes). Inside Lean's logic, #eval establishes nothing: it builds no proof term. The auxiliary definition that it compiles for the expression is discarded afterward, and no typing rule of Section 6 mentions the compiler; that compiled code computes what the mathematical equations specify is never formally proved inside Lean. A value printed by #eval is strong empirical evidence for a definitional equality, not a kernel certificate. Compiled execution enters a proof only through dedicated tactics such as native_decide (Section 10.4) and bv_decide (Section 10.5), each of which records an explicit axiom dependency on the resulting theorem.

One definition, two evaluatorsread across: a row is the same question, asked of the kernel and of the compiler

  1. is given

    a term without recursion The definition after a second translation: every recursive call replaced by a recursor or a well-founded fixpoint, with the proofs that this takes.

    the definition as written The pre-definition: pattern matching already replaced by auxiliary functions, recursion intact.

  2. computes by

    reducing the term The rules of definitional equality, applied until a value shows.

    running code #eval, or a binary · #eval runs the compiled code in an interpreter; built into a binary, the same code is native.

  3. its answer is

    an equality of the logic rfl, decide · rfl and decide are accepted because the kernel brings both sides to the same value. The computation is part of checking the proof.

    a printed value No proof is built, and the auxiliary definition compiled for the expression is not kept: nothing has been proved.

  4. a recursion with no reason to end

    refused, or opaque Without a reason the definition is refused. Marked partial, it reaches the kernel as a constant with a type and no equation.

    compiled like any other A partial definition runs as it was written, for as long as it runs.

  5. is trusted

    it is the checker What the kernel accepts is what checked means. Who checks the kernel is a question of its own.

    only as an axiom native_decide, bv_decide · Compiled code enters a proof through tactics made for that, and each time as a named axiom that the theorem then carries.

green: the one answer that can stand in a proof

Still unexplained is why one line, added to the equations of fib, changed the term the kernel was handed.

Why a recursion ends, and what the kernel receives

The line that fibW adds is a reason. Lean asks of a recursive definition a reason why it ends, and what reaches the kernel depends on the reason. Five definitions show the range: the factorial three times, with the reason in the structure of its argument (factS), in a measure that decreases (factW), and with the reason waived (factP); halvings, which counts how often a number can be halved; and Ackermann's function, ack.

table    five recursive definitions as Lean 4.35.0 handed them to its kernel (recorded), and who computes with each

         definition  recursion                     the kernel receives                  nodes  in proofs  rfl  decide  decide   simp  #eval
                                                                                                                       +kernel
         factS       structural                    Nat.brecOn, over Nat.rec               168          0  yes  yes     yes      yes   yes
         factW       well-founded                  WellFounded.Nat.fix, over Nat.rec    4,164      3,893  no   no      yes      yes   yes
         halvings    well-founded, not structural  WellFounded.Nat.fix, over Nat.rec   25,843     25,656  no   no      yes      yes   yes
         ack         well-founded, on a pair       WellFounded.fix, over Acc.rec       40,287     39,157  no   no      no       yes   yes
         factP       partial                       an opaque constant                      63          0  no   no      no       no    yes

         in focus: factW, 85 characters as written, 8 declarations for the kernel. Its term, with the names
         the author did not write between marks:
           »WellFounded.Nat.fix« (fun x => x) fun a a_1 => (match ... | n».succ« => fun x => (n + 1) * x n (»factW._proof_1« n)) a_1
         asked   example : factW 5 = 120 := rfl
         Lean    Type mismatch: rfl has type ?m.7 = ?m.7 but is expected to have type factW 5 = 120
(the live figure needs JavaScript and loads about 0.06 MB)
Five recursive definitions, a row each, as Lean 4.35.0 handed them to its kernel: a recording. Green: what the author did not write, in the table the growth in nodes from the body as written (ring) to everything the kernel checked (dot), with a tick where the proofs begin, and in the term the names Lean put in. The grid asks Lean to compute with each definition in seven ways; where it refuses or gets stuck the cell is hatched, and its answer stands below in its own words. Choose a definition, or click a cell.

What the author wrote is a small part of what the kernel checked. The three lines of factS reach it as 168 nodes of term, counting a term as a tree. The same equations with a measure, the 85 characters of factW, reach it as 8 declarations of 4,164 nodes, 3,893 of them in theorems that the author never stated, among them that the recursive call is on something smaller and that the function satisfies its equations. For halvings the count is 25,843 nodes, 25,656 of them in such theorems, and for ack 40,287 and 39,157. The kinds of recursion differ also in who can compute with them: with factS every way of asking does, with factP only #eval.

That Lean insists on a reason at all is a matter of logic before it is one of programming.

Unlike many languages, Lean ensures by default that every recursive function will eventually reach a base case. From a programming perspective, this rules out accidental infinite loops. But this feature is especially important when proving theorems, where infinite loops cause major difficulties.

—David Thrane Christiansen, "Functional Programming in Lean". Section 1.5, "Datatypes and Patterns" (lean-lang.org/functional_programming_in_lean). The paragraph ends with one sentence more, which leads into a recursive definition that Lean does not accept. The book's release history says that it was updated in October 2025 to Lean 4.23.0; nothing quoted from it here depends on the version.

The difficulty shows on a definition that has no reason to give.

def f (n : Nat) : Nat := f n + 1

Were this accepted, its equation f n = f n + 1 would be a theorem, and no natural number is its own successor: the logic would prove False. Lean refuses, in these words.

error: fail to show termination for
  f
with errors
failed to infer structural recursion:
Not considering parameter n of f:
  it is unchanged in the recursive calls
no parameters suitable for structural recursion

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

The message names the two reasons that Lean looks for. The first is structural recursion (Definition 8.1.1). The kernel receives it as the recursor of the type, through brecOn, as in Section 8.2, and the equations of the definition hold by computation: rfl proves factS 5 = 120.

The second is the general one, for a call such as halvings (n / 2), whose argument is smaller than n and no part of it: something gets smaller at every call, in an order in which nothing gets smaller for ever, the property that carried the proofs of Sections 3.3 and 3.5. Lean states the notion inductively.

Definition 8.3.1 (accessible, well-founded). Let r be a relation on a type α, and read r y x as: y is below x. The proposition Acc r x, that x is accessible, is the inductive proposition with one constructor: if every y below x is accessible, then x is accessible. The relation is well-founded, WellFounded r, if every x is accessible.

With classical logic and dependent choice, WellFounded r is equivalent to saying that no infinite chain \(x_0, x_1, x_2, \dots\) descends along r. Stated inductively via Acc, however, well-foundedness gives type theory something concrete to recurse on. In halvings n, the recursive argument n / 2 is computed by division rather than stripped off a constructor, so Nat.rec cannot recurse structurally on n. Instead, Lean recurses structurally on the accessibility proof tree Acc r x: because Acc.intro x h packs a sub-proof h y _ : Acc r y for every y below x, every recursive call at a smaller y steps into a direct constructor child of that proof tree, using the one form of recursion the kernel accepts. A library theorem packages that trick into a general fixpoint combinator and proves its unfolding equation.

Theorem 8.3.2 (recursion along a well-founded relation; Lean's core library). Let hwf : WellFounded r, let C : α → Sort v be a family of types, and let F : ∀ x, (∀ y, r y x → C y) → C x compute a value at x from the values at everything below x. Then there is a function WellFounded.fix hwf F : ∀ x, C x which satisfies, for every x, the equation fix hwf F x = F x (fun y _ => fix hwf F y).

/--
A well-founded fixpoint. If satisfying the motive `C` for all values that are smaller according to a
well-founded relation allows it to be satisfied for the current value, then it is satisfied for all
values.

This function is used as part of the elaboration of well-founded recursion.
-/
-- Well-founded fixpoint
noncomputable def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
  fixF F x (apply hwf x)

-- Well-founded fixpoint satisfies fixpoint equation
theorem fix_eq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) :
    fix hwf F x = F x (fun y _ => fix hwf F y) :=
  fixF_eq F x (apply hwf x)

Proof (the idea, as the core library of Lean 4.35.0 has it). The recursion is structural (Definition 8.1.1), not on x but on the proof that x is accessible. That proof holds a proof for every y below x, so the recursor of Acc supplies the values below x that F asks for; this is fixF. The equation is proved by induction on the same proof, and passing from one proof of accessibility to another costs nothing, because two proofs of one proposition are definitionally equal (Section 6.3). ∎

Two words of the listing carry weight. noncomputable tells the compiler not to try: fix exists for the kernel, and compiled code is made from the definition as written. And C is a family of types, not only of propositions: in Lean 4.35.0 Acc is a proposition from whose proofs data may be computed, the large elimination of Section 6.5. The price of the construction is in the reference's own summary.

For straightforwardly structurally recursive functions, the translation will use the type's recursor. These functions tend to be relatively efficient when run in the kernel, their defining equations hold definitionally, and they are easy to understand. Functions that use other patterns of recursion that cannot be captured by the type's recursor are translated using well-founded recursion, which is structural recursion on a proof that some measure decreases at each recursive call, or using partial fixpoints, which logically capture at least part of a function's specification by appealing to domain-theoretic constructions. Lean can automatically derive many of these termination proofs, but some require manual proofs. Well-founded recursion is more flexible, but the resulting functions are often slower to execute in the kernel due to the proof terms that show that a measure decreases, and their defining equations may hold only propositionally. To provide a uniform interface to functions defined via structural and well-founded recursion and to check its own correctness, the elaborator proves equational lemmas that relate the function to its original definition. In the function's namespace, eq_unfold relates the function directly to its definition, eq_def relates it to the definition after instantiating implicit parameters, and N lemmas eq_N relate each case of its pattern-matching to the corresponding right-hand side, including sufficient assumptions to indicate that earlier branches were not taken.

—"The Lean Language Reference", edition for Lean 4.35.0. The same section, "Elaboration Results": the paragraph whole. The equational lemmas of its last two sentences are what simp [ack] rewrites with.

"Only propositionally" means that the defining equation holds as a proved theorem (fix_eq and the generated eq_N lemmas) for tactics to rewrite with, rather than by rfl alone. In Lean 4.35.0, well-founded definitions split into two subcases depending on the measure. When the measure is a natural number (factW and halvings), Lean compiles the recursion to WellFounded.Nat.fix, which recurses structurally on a Nat fuel counter initialized one above the measure; the kernel can evaluate that counter directly, so decide +kernel accepts factW 5 = 120. Plain rfl and decide still fail only because Lean marks factW irreducible to keep the elaborator's own reducer from unfolding bulky proof terms; lifting that mark with unseal factW in lets rfl succeed. When the measure is a lexicographic pair (ack), the Nat counter shortcut does not apply and the definition compiles to WellFounded.fix over Acc.rec, sealed behind an opaque constant; even without that seal, computing via Acc.rec in the kernel would mean reducing large accessibility proofs that were never meant to compute. Among the proof tactics in the table, only simp [ack], which rewrites propositionally using the proved equational lemmas, evaluates ack.All of this is Lean 4.35.0, and this corner of Lean is moving. A change merged on 14 October 2026 and first released in the candidate 4.37.0-rc1 has well-founded recursion no longer eliminate Acc into data: "The one visible change is that well-founded definitions now depend on Classical.choice, which #print axioms reports." A second, merged on the evening of 20 November 2026 in New York and in no release as of 1 December, restricts Acc.rec to motives in Prop (Lean's pull requests 14892 and 13851).

The proofs leave one more trace. #print axioms (Section 7.5) reports no axiom for factS, propext for factW, and propext and Quot.sound for halvings and ack, whose authors invoked none: the axioms came in with the proofs that Lean found. Its proof that n / 2 is below n when n is at least 2 is a term of 24,163 nodes.

A reason can also be waived, and f says what to fear: an equation that proves False.

Remark 8.3.3 (partial is not a hole in the logic). Marked partial, the definition without a reason is accepted.

partial def g (n : Nat) : Nat := g n + 1
#print g
opaque g : Nat → Nat

The kernel receives a constant with a type and no equation; Lean asks only that the type have an element. So g 0 = g 0 + 1 cannot be proved, rfl is refused with Type mismatch, and #print axioms g reports none. What is lost is not consistency but every theorem that would need the equation. The compiler receives the equation as written, and #eval g 0, run from the command line, recurses until Lean's guard on the depth of its stack ends the process itself, with deep recursion was detected at 'interpreter'.

One loose end goes back to 2 + 3: the examples write +, and the function is called Nat.add.

Type classes are records passed silently

In Lean's source the addition of Section 8.1 is followed by two more lines.

instance instAddNat : Add Nat where
  add := Nat.add

They are what makes 2 + 3 mean Nat.add 2 3. Add is a type class, which is a structure, here with one field. Lean prints it so.

class Add.{u} (α : Type u) : Type u
number of parameters: 1
fields:
  Add.add : α → α → α
constructor:
  Add.mk.{u} {α : Type u} (add : α → α → α) : Add α

An instance is an element of the structure, registered for a search: here the record whose field add is Nat.add. A function asks for such a record in square brackets.

def double [Add α] (x : α) : α := x + x

#eval double 21                           -- 42
#eval double 1.5                          -- 3.000000

instance pointwise {α β : Type} [Add β] : Add (α → β) where
  add f g := fun x => f x + g x

#eval double (fun n : Nat => n * n) 3     -- 18

double works unchanged on Nat, on Float, and, once pointwise defines addition on functions, on Nat → Nat as well. Although the call writes no dictionary by hand, Lean passes one silently behind the scenes. Setting set_option pp.explicit true prints the elaborated term behind double (fun n : Nat => n * n) in full.

@double (Nat → Nat) (@pointwise Nat Nat instAddNat) fun n =>
  @HMul.hMul Nat Nat Nat (@instHMul Nat instMulNat) n n : Nat → Nat

The second argument @pointwise Nat Nat instAddNat is the synthesized record: pointwise addition on Nat → Nat, built from instAddNat on Nat. The elaborator assembled it automatically by searching through registered instances, a procedure Section 9.4 traces step by step. Type classes add no new construct to the kernel; they simply pair ordinary structures with an elaborator search triggered by square-bracket parameters.

Definition 8.4.1 (type class, instance). A type class is a structure declared with class (or, rarely, another inductive type, declared with class inductive). An instance is a definition of an element of it, declared with instance, which registers the element for the search. An argument written in square brackets, as in [Add α], is filled by the elaborator with the result of the search; if the search finds nothing, the elaboration fails.

The kernel knows none of these words. It receives structures, definitions and applications, and the failure belongs to the elaborator: #eval double "ab" is answered failed to synthesize instance of type class Add String. The reference gives the purpose as overloading: "the canonical use case is for overloading arithmetic operators so that they work with Nat, Int, Float, and any other type that has a sensible notion of addition"."The Lean Language Reference", Section 10, "Type Classes", which credits the idea in a note in its margin: "Type classes were first described in Philip Wadler and Stephen Blott, 1989." One + for all of mathematics is built on this (Section 11.3), and so is the notion of Section 8.5, which gives a language of functions what a tactic needs: state, and failure.

Effects are data

A pure language has no variable to assign and no exception to raise. Here is a program that keeps a counter all the same, and can fail: tick reads the fuel that is left, stops with an error if there is none, and otherwise writes back one unit less.

stages   a program of 5 lines in do notation (tick: spend one unit of fuel; an error when none is left),
         unfolded in 8 stages (recorded from Lean 4.35.0): nodes of the term, characters as printed

           1 source                                         79 characters
             printed by Lean
           2 as Lean prints it                 270 nodes    200
           3 without notation                  270          163
           4 everything explicit               270          1,396
             computed for the recording, with Lean's own unfolding; Lean accepts the last by rfl
           5 instances opened                  194          204
           6 unfolded: StateT's functions      228          304
           7 unfolded: Except's functions      122          148
         ▸ 8 local definitions substituted     105          108

         fun s =>
           (if s = 0 then fun s => Except.error "out of fuel" else fun x => Except.ok (PUnit.unit, s - 1)) s

thread   three ticks from fuel 2, by that function, evaluated in the page; the state is what the thread carries
           2 ── tick 1 ── 1 ── tick 2 ── 0 ── tick 3 ✕      the program returns Except.error "out of fuel"
(the live figure needs JavaScript and loads about 0.01 MB)
A program of five lines in do notation, with a state and an exception, unfolded in eight stages: a recording of Lean 4.35.0. Lean prints the first four; the last four were computed for the recording with Lean's own unfolding, and Lean accepts the last by rfl. Green: the state as it is threaded, a rule under every place it went when the page ran that term, and the thread from tick to tick. The last stage is read from the recording and applied three times by an evaluator in the page; grey is the branch not taken. Step through the stages; move the fuel.

Unfolded, the five lines are a function from a state to an error or a result paired with a new state, Nat → Except String (PUnit × Nat), and Lean accepts rfl between the two. The notation was hiding a function and nothing else. Of the eight stages the first is the source and the next three are Lean's own printing of the elaborated term; the last four were computed for the recording, with Lean's own functions for unfolding a definition, and the rfl is Lean's check that the last of them is the program it started from. After throw nothing more runs: in the unfolded term the continuation of the error is never entered, so the state is not threaded through it.

The idea is older than Lean and comes from the semantics of programming languages. A program that takes an \(A\) and returns a \(B\), and that may also fail, or read and change a store, is not a function from \(A\) to \(B\). Eugenio Moggi's proposal was to keep functions and change the target: such a program is a function from \(A\) to \(T\,B\), where \(T\,B\) is the type of computations of a \(B\). For failure, a computation of a \(B\) is a \(B\) or an error; for a store of type \(S\), it is a function \(S \to B \times S\).

The λ-calculus is considered an useful mathematical tool in the study of programming languages, since programs can be identified with λ-terms. However, if one goes further and uses βη-conversion to prove equivalence of programs, then a gross simplification is introduced (programs are identified with total functions from values to values), that may jeopardise the applicability of theoretical results. In this paper we introduce calculi based on a categorical semantics for computations, that provide a correct basis for proving equivalence of programs, for a wide range of notions of computation.

—Eugenio Moggi, "Notions of computation and monads", abstract. Quoted from the author's version of the paper (a copy at Carnegie Mellon), which carries no date. Its first example lists the notions it has in mind: partiality, nondeterminism, side-effects, exceptions, continuations, interactive input and interactive output. P. Wadler, "Monads for functional programming", in Advanced Functional Programming, Springer LNCS 925, 1995, carried the idea from semantics into programs: "The concept of a monad, which arises from category theory, has been applied by Moggi to structure the denotational semantics of programming languages".

Lean takes the simplification at its word. Its programs are total functions from values to values, by Sections 8.1 and 8.3, so whatever else a program does has to stand in its type, as a \(T\). What makes that workable is that functions into \(T\) can be composed, and this is the whole definition.

Definition 8.5.1 (monad). A monad is a map \(m\) from types to types with two operations,

\[\mathrm{pure} : \alpha \to m\,\alpha, \qquad \mathrm{bind} : m\,\alpha \to (\alpha \to m\,\beta) \to m\,\beta,\]

the second written \(x \mathbin{\gg\!=} f\) for \(\mathrm{bind}\,x\,f\), such that for all \(a\), \(x\), \(f\) and \(g\)

\[\mathrm{pure}\,a \mathbin{\gg\!=} f \;=\; f\,a, \qquad x \mathbin{\gg\!=} \mathrm{pure} \;=\; x, \qquad (x \mathbin{\gg\!=} f) \mathbin{\gg\!=} g \;=\; x \mathbin{\gg\!=} (\lambda a.\; f\,a \mathbin{\gg\!=} g).\]

An element of \(m\,\alpha\) is a computation that returns an \(\alpha\). pure a returns a and does nothing else; x >>= f runs x and then f on what it returned. The laws say that this way of composing functions \(\alpha \to m\,\beta\) is associative and has pure as its unit. A reader who knows monads from category theory has the same notion here, on the category of types, presented by its Kleisli extension \(f \mapsto (x \mapsto x \mathbin{\gg\!=} f)\) and not by a multiplication. In Lean, Monad is a type class (Section 8.4) whose instances supply the two operations. The laws belong to a second class, LawfulMonad: the first and the third are among its fields, as pure_bind and bind_assoc, and the second, bind_pure, is a theorem proved from its other fields. An instance of Monad may come with a proof of them or without.

The figure unfolded two monads, one on the other. Their binds are what it showed: the state handed on, nothing run after an error.

Example 8.5.2 (state and failure). Look at the two monads stacked inside tick as Lean's core library defines them. Except ε α is the inductive type with two constructors, Except.error carrying an error ε and Except.ok carrying a value α; its bind passes an error along unchanged and applies the continuation to the payload of ok. StateT σ m α is defined as the function type σ → m (α × σ), whose bind runs the first step on the incoming state and passes both the returned value and the updated state to the next step. Stacking StateT over Except combines both effects: asked #reduce (types := true) StateT Nat (Except String) Unit, Lean answers Nat → Except String (PUnit × Nat). Inside do notation, writing let a ← x before the rest of a block desugars to x >>= fun a => .... Evaluated on concrete fuel counts, tick.run 3 returns Except.ok ((), 2) and tick.run 0 returns Except.error "out of fuel". ◁

So the type of tick names its two effects, and Section 8.6 reads a tactic's type the same way.

Lean is a pure functional language. This means that it does not include side effects such as mutable variables, logging, or exceptions. However, most side effects can be encoded using a combination of functions and inductive types or structures. For example, mutable state can be encoded as a function from an initial state to a pair of a final state and a result, and exceptions can be encoded as an inductive type with constructors for successful termination and errors.

Each set of encoded effects is a type. As a result, if a program uses these encoded effects, then this is apparent in its type. Functional programming does not mean that programs can't use effects, it simply requires that they be honest about which effects they use. A Lean type signature describes not only the types of arguments that a function expects and the type of result that it returns, but also which effects it may use.

—David Thrane Christiansen, "Functional Programming in Lean". Section 4.7.1, "Encoding Side Effects", in the summary of the chapter on monads: the two paragraphs are the whole of it.

The honesty has a price in terms, which the elaborator pays. The five lines of tick are a term of 270 nodes as elaborated, and 1,396 characters when Lean prints every instance that it passed; unfolded to the function on the state they are 105 nodes.

One picture of a monad has to be dropped before Section 8.6, whose four monads it does not fit.

Remark 8.5.3 (a monad is not a container). Option, the type of values that may be absent, forms a monad, making it tempting to picture every \(m\,\alpha\) as a box holding elements of \(\alpha\). The state monad holds nothing at all: an inhabitant of StateT σ m α is a function waiting for an initial state. What pure and bind provide is not a box, but a disciplined way to sequence steps that thread context, update state, or abort early.

State and failure were built for a program still missing: one that reads a goal and writes a term.

Lean in Lean: a tactic is a program

Everything that happens between a line of source and the term the kernel checks is done by programs written in Lean, in monads, and a user can add to them. Here is one addition, a tactic of eleven lines that turns a goal a ∧ b into two goals, run on four goals.

program  a tactic of 11 lines, written in Lean, run by Lean 4.35.0 on four goals (recorded); here the goal p ∧ q

          1  /-- `split_and` proves a goal `a ∧ b` from two new goals, `a` and `b`. -/
          2  elab "split_and" : tactic => do
          3    let goal ← getMainGoal                                      goal        ⊢ p ∧ q
          4    let target ← whnfR (← goal.getType)                         target      p ∧ q         (read)
          5    match target.and? with                                      target.and? some (p, q)
          6    | none => throwError "split_and: the goal is not a conjunction:{indentExpr target}"
          7    | some (a, b) =>
          8      let left ← mkFreshExprSyntheticOpaqueMVar a (tag := `left)     left   ?left : p
          9      let right ← mkFreshExprSyntheticOpaqueMVar b (tag := `right)   right  ?right : q
       ▸ 10      goal.assign (mkApp4 (mkConst ``And.intro) a b left right)      writes ⟨?left, ?right⟩
         11      replaceMainGoal [left.mvarId!, right.mvarId!]                  leaves 2 goals: ⊢ p and ⊢ q

         then exact hp and exact hq fill the two holes: 3 tactics in all build fun p q hp hq => ⟨hp, hq⟩
(the live figure needs JavaScript and loads about 0.02 MB)
A tactic of eleven lines, written in Lean and run by Lean 4.35.0 on four goals: a recording, walked through a line at a time. Beside the tactic, with the line being run marked: its variables as its lines bind them; the goals, a grey ground on what a line took or read; the proof term so far. Green: the term the tactics build, a rule under what is written; a frame is a hole still to be filled. The last option runs the same tactic with two arguments exchanged: every step is accepted, and the kernel refuses the term. Step, or choose a goal.

Inside Lean, an open proof goal is simply an unassigned metavariable (a typed hole) sitting inside a partial proof term, and a tactic is a monadic program that inspects that hole's target type and assigns it an expression possibly containing new holes, which become the remaining subgoals. On ⊢ p ∧ q, split_and creates two fresh holes ?left : p and ?right : q, assigns the original goal @And.intro p q ?left ?right (⟨?left, ?right⟩), and puts ?left and ?right on the goal list; exact hp and exact hq then fill those two holes, completing the term fun p q hp hq => ⟨hp, hq⟩. Once the holes are filled, no trace of the tactics remains: only that pure kernel term is stored and checked (Section 10.1 follows such terms step by step).

Swapping the two arguments of And.intro inside split_and gives the run worth remembering. Every tactic step succeeds without complaint, assembling the term fun p q hp hq => ⟨hq, hp⟩, and at the end of the proof the kernel rejects the declaration.

(kernel) declaration type mismatch, 'swapped' has type
  ∀ (p q : Prop), p → q → q ∧ p
but it is expected to have type
  ∀ (p q : Prop), p → q → p ∧ q

The tactic framework runs the wrong tactic without complaint; it is the kernel that refuses the term: search is not trusted, checking is. Section 10.7 makes a principle of it.

To have all of Lean's internals at hand, the tactic needed one line, import Lean, and that was a design goal.

Lean 4 is a reimplementation of the Lean interactive theorem prover (ITP) in Lean itself. It addresses many shortcomings of the previous versions and contains many new features. Lean 4 is fully extensible: users can modify and extend the parser, elaborator, tactics, decision procedures, pretty printer, and code generator. The new system has a hygienic macro system custom-built for ITPs. It contains a new typeclass resolution procedure based on tabled resolution, addressing significant performance problems reported by the growing user base. Lean 4 is also an efficient functional programming language based on a novel programming paradigm called functional but in-place. Efficient code generation is crucial for Lean users because many write custom proof automation procedures in Lean itself.

—Leonardo de Moura and Sebastian Ullrich, "The Lean 4 Theorem Prover and Programming Language" (2021). The abstract of the system description in the proceedings of CADE 28, Springer LNCS 12699, 2021 (the authors' copy).

The programs work on three kinds of data, each an ordinary Lean type, and the definition of a tactic needs all three. Syntax is what the parser returns: an inductive type, Syntax, with four constructors. Expressions are the terms of Section 6.1, the type Expr, one of whose twelve kinds is the metavariable, the named hole of Section 9.2. And the environment is the collection of all declarations made so far, which Lean's sources describe so.

/--
An environment stores declarations provided by the user. The kernel
currently supports different kinds of declarations such as definitions, theorems,
and inductive families. Each has a unique identifier (i.e., `Name`), and can be
parameterized by a sequence of universe parameters.
A constant in Lean is just a reference to a `ConstantInfo` object. The main task of
the kernel is to type check these declarations and refuse type incorrect ones. The
kernel does not allow declarations containing metavariables and/or free variables
to be added to an environment. Environments are never destructively updated.
-- ...
-/
structure Environment where
  /--
  The constructor of `Environment` is private to protect against modification that bypasses the
  kernel.
  -/
  private mk ::

An environment is a value: adding a declaration returns a new one, and the ordinary road into it leads through the kernel. The ways around that road, and the gates that close them, are the matter of Section 13.6. A theorem is an entry in this table, and a program can look it up.

import Lean
open Lean Meta

#eval show MetaM Unit from do
  let env ← getEnv
  let some c := env.find? ``Nat.add_comm | throwError "unknown constant"
  logInfo m!"{c.name} : {c.type}"
Nat.add_comm : ∀ (n m : Nat), n + m = m + n

Between syntax and expressions stand two kinds of program. A macro is a function from syntax to syntax. Two lines give Lean a summation sign, and #check shows what the sign stands for.

macro "∑ " i:ident " < " n:term ", " f:term : term =>
  `(List.foldl (· + ·) 0 ((List.range $n).map fun $i => $f))

#eval ∑ i < 5, i * i      -- 30
#check ∑ i < 5, i * i
List.foldl (fun x1 x2 => x1 + x2) 0 (List.map (fun i => i * i) (List.range 5)) : Nat

The names that a macro introduces and the names that its user wrote cannot capture one another, a property called hygiene.S. Ullrich and L. de Moura, "Beyond Notations: Hygienic Macro Expansion for Theorem Proving Languages", arXiv 2001.10490 (January 2020, seventh version April 2022). In the tactic languages of earlier provers, its abstract says, the trouble was "accidental name capture, which often produces unexpected and counterintuitive behavior". In Lean's sources a macro has the type Syntax → MacroM Syntax, and an elaborator of terms the type Syntax → Option Expr → TermElabM Expr, where the optional expression is the type that is expected. A tactic's type has the same shape, with Unit for a result: it says what a tactic may touch, not that the term it assigns proves the goal.

Definition 8.6.1 (tactic). A tactic is a function of type Syntax → TacticM Unit: from the syntax of its call to an action which may read the environment and the goals, assign a term to the metavariable of a goal, and replace the list of goals.

Lean's sources say it in one line.

/--
A tactic is a function from syntax to an action in the tactic monad.
-- ...
-/
abbrev Tactic  := Syntax → TacticM Unit

Or, as the community's book on the subject has it, "All tactics are, in the end, of type TacticM Unit."A. Paulino, D. Testa, E. Ayers, E. Karunus, H. Böving, J. Limperg, S. Gadgil and S. Bhat, "Metaprogramming in Lean 4" (github.com/leanprover-community/lean4-metaprogramming-book, at its commit of 18 November 2026), the opening of the chapter "Tactics". The account of the four monads follows the opening of its chapter "MetaM". TacticM is the last of four monads, each of which is the one before it with more to read and more state to keep.

The four monads Lean is written inread downward: each monad is the one above it with a context to read and a state to keep; in ink, its definition in Lean's sources

  1. 8.6CoreM the environment

    Every declaration made or imported so far, the options in force, the namespace that is open.

    abbrev CoreM := ReaderT Context <| StateRefT State (EIO Exception)

  2. 9.2MetaM terms with holes

    The metavariables declared so far, the holes of terms, and the terms assigned to them.

    abbrev MetaM := ReaderT Context $ StateRefT State CoreM

  3. 8.6TermElabM elaboration

    The information that turning syntax into a term needs along the way.

    abbrev TermElabM := ReaderT Context $ StateRefT State MetaM

  4. 8.6TacticM the goals

    The list of goals still open. A tactic is a function from syntax to an action in this monad.

    abbrev TacticM := ReaderT Context $ StateRefT State TermElabM

green: the monad a tactic runs in

By Section 8.5 all four are functions. Asked to unfold the type TacticM Unit all the way, Lean prints a function type whose first eight arguments are four contexts and four references to mutable state.

Not all of Lean is written in Lean, and one part that is not is the part on which the argument of this series rests. "Lean's kernel is written in C++", the reference says, and continues: "There are independent re-implementations in Rust and Lean, and the Lean project is interested in having as many implementations as possible so that they can be cross-checked against each other." Section 13.4 takes them up.

In Lean

Because propositions are types and proofs are terms, a theorem proved by induction can be written with the exact same recursive function syntax as a program. In a standalone file that imports nothing, define sum on lists, run both evaluators on it, and prove sum_append by pattern matching.

def sum : List Nat → Nat
  | [] => 0
  | x :: xs => x + sum xs

#eval sum [1, 2, 3, 4]                        -- 10
example : sum [1, 2, 3, 4] = 10 := rfl

theorem sum_append : ∀ xs ys : List Nat, sum (xs ++ ys) = sum xs + sum ys
  | [], ys => (Nat.zero_add (sum ys)).symm
  | x :: xs, ys => by
    show x + sum (xs ++ ys) = x + sum xs + sum ys
    rw [sum_append xs ys, Nat.add_assoc]

#print sum
#print sum_append
#print axioms sum_append
def sum : List Nat → Nat :=
fun x => List.brecOn x sum._f
theorem sum_append : ∀ (xs ys : List Nat), sum (xs ++ ys) = sum xs + sum ys :=
fun x x_1 => List.brecOn (motive := fun x => ∀ (x_2 : List Nat), sum (x ++ x_2) = sum x + sum x_2) x sum_append._f x_1
'sum_append' does not depend on any axioms

The theorem is written as a recursive function on its first list, and the call sum_append xs ys in its second case is the induction hypothesis. Lean checked that the call is on a part of the argument and translated the function and the proof by one device: both are List.brecOn, and the motive of the second, the family that says what the recursion builds at each list, is the statement of the theorem. A proof by induction is a structurally recursive program, which is Section 4 at work.

Next, a dozen lines define a custom tactic my_assumption that loops over the local context of hypotheses in scope and closes the goal with the first hypothesis whose type is definitionally equal to the target.

import Lean
open Lean Elab Tactic Meta
/-- Close the goal with a hypothesis whose type is definitionally equal to it. -/
elab "my_assumption" : tactic => do
  let goal ← getMainGoal
  goal.withContext do
    let target ← goal.getType
    for decl in ← getLCtx do
      if decl.isImplementationDetail then continue
      if ← isDefEq decl.type target then
        logInfo m!"read: {target}; wrote: {decl.toExpr}"
        goal.assign decl.toExpr
        return
    throwError "my_assumption: no hypothesis has type {target}"

It reads the type of the goal and the hypotheses in scope, asks isDefEq, the elaborator's test of definitional equality, and assigns the goal the first hypothesis that passes. Lean's own constructor splits a conjunction as the tactic of Section 8.6 does, and the two together prove one.

theorem both (p q : Prop) (hp : p) (hq : q) : p ∧ q := by
  constructor
  my_assumption
  my_assumption

#print both

example (p q : Prop) (hp : p) : p ∧ q := by
  constructor
  my_assumption
  my_assumption
read: p; wrote: hp
read: q; wrote: hq
theorem both : ∀ (p q : Prop), p → q → p ∧ q :=
fun p q hp hq => ⟨hp, hq⟩
read: p; wrote: hp
error: my_assumption: no hypothesis has type q

The last two lines belong to the example, which has no proof of q to offer. The tactic fails with its own message. Lean reports the error and goes on: it puts sorry in the hole that was left, and the kernel still receives a term. Stated as a theorem, the same lines leave fun p q hp => ⟨hp, sorry⟩, and #print axioms (Section 7.5) names sorryAx under it.

Lean's logic is also the language that Lean is written in. A definition is run by two evaluators, and only what the kernel computes can stand in a proof; everything else that runs, a tactic included, is a program whose output the kernel has to check.

The largest of these programs is the one that turns a line of mathematics into a term. The line leaves out most of what the kernel must have, and Section 9 asks what puts it back.

← Back to all posts