Module 2: Programming in Lean·Lesson 6 of 16·2 min read

Why Lean Refuses a Function That Might Never Stop

The problem: a function that never finishes

In most languages you can write a function that calls itself forever, and the compiler will not stop you. The program just hangs when you run it. That is annoying in programming. In a proof assistant it is a disaster.

Here is why. A function in Lean promises to return a value of its type. If a function could loop forever, you could "define" a value of any type without ever producing one, including a proof of a false statement. So Lean requires every ordinary function to terminate. This lesson shows how that works and what to do when Lean is not convinced.

Structural recursion: the easy case

Recursion means a function calls itself. The safest kind follows the shape of an inductive type: you call yourself only on a smaller piece of the input.

lean
def factorial : Nat -> Nat
  | 0 => 1
  | n + 1 => (n + 1) * factorial n

#eval factorial 5
#eval factorial 20

Lean prints:

lean
-- 120
-- 2432902008176640000

The pattern n + 1 matches any number that is one more than some n, which is the Nat.succ case from the previous lesson. In that case, factorial calls itself on n, which is strictly smaller than n + 1. Since every natural number is built from zero by finitely many successors, the calls must hit 0 eventually. This is called structural recursion, and Lean accepts it automatically.

Notice that factorial 20 printed a very large number with no overflow. Lean's Nat has no fixed size, so it grows as needed.

Recursion on lists

Lists work the same way. Handle the empty list, and in the x :: xs case, recurse on the tail xs:

lean
def sumList : List Nat -> Nat
  | [] => 0
  | x :: xs => x + sumList xs

#eval sumList [1, 2, 3, 4]

def countDown : Nat -> List Nat
  | 0 => [0]
  | n + 1 => (n + 1) :: countDown n

#eval countDown 5

Lean prints:

lean
-- 10
-- [5, 4, 3, 2, 1, 0]

In sumList, each call works on a shorter list, so it must end. In countDown, each call works on a smaller number. Both are structural, and you did not have to explain anything to Lean.

When Lean says no

Now write a function that clearly runs forever:

lean
def forever (n : Nat) : Nat := forever (n + 1)

Lean rejects the definition. The message begins:

lean
-- error: fail to show termination for
--   forever
-- with errors
-- failed to infer structural recursion:

and ends with the goal it could not prove:

lean
-- n : Nat
-- ⊢ n + 1 < n

This is worth reading closely. Lean first tried structural recursion and failed, because n + 1 is not a smaller piece of n. Then it tried to prove that the argument goes down on each call, and it got stuck needing n + 1 < n, which is false. Lean shows you exactly what it would need to believe. The ⊢ symbol means "this is what remains to be proved", and you will see it constantly once you start using tactics.

Animation: factorial calls itself on a smaller number until it reaches 0. forever only climbs, so Lean rejects it.

Beyond structural: Lean can sometimes prove it for you

Not every terminating function follows the structure of its input. Here is one that halves its argument:

lean
def halvings (n : Nat) : Nat :=
  if n < 2 then 0 else 1 + halvings (n / 2)

#eval halvings 1000

Lean prints:

lean
-- 9

halvings calls itself on n / 2, which is not a constructor piece of n. Lean accepted it anyway. When structural recursion does not apply, Lean tries to show that some measure of the arguments decreases on every call, and here its built in automation could show that n / 2 < n in the branch where n is at least 2. When the automation fails, you can help with termination_by and decreasing_by, which the error message above mentioned. Those are beyond this lesson, but now you know what they are for.

The escape hatch: partial

Some functions might terminate, but nobody knows how to prove it. The famous Collatz process is one: halve even numbers, triple odd ones and add one, and count steps to reach 1. Whether this always reaches 1 is an open problem in mathematics.

You can still run it by marking the function partial:

lean
partial def collatzSteps (n : Nat) : Nat :=
  if n <= 1 then 0
  else if n % 2 == 0 then 1 + collatzSteps (n / 2)
  else 1 + collatzSteps (3 * n + 1)

#eval collatzSteps 27

Lean prints:

lean
-- 111

The price is that Lean treats a partial function as a black box. You can run it with #eval, but you cannot prove anything about what it computes, because Lean does not let its definition be unfolded in proofs. This is a fair trade: you keep running code, and the logic stays safe.

Why this rule keeps proofs honest

The termination rule ties straight back to lesson one. Lean's guarantee is that a proof checked by the kernel really proves its statement. If non terminating definitions were allowed in the logic, you could "prove" any statement with a definition that just calls itself forever and never produces anything. Requiring termination closes that hole.

So when Lean rejects a recursive function, it is not being picky. It is protecting every proof you will write later.

Try this

Paste into https://live.lean-lang.org:

lean
def myLength : List Nat -> Nat
  | [] => 0
  | _ :: xs => 1 + myLength xs

#eval myLength [4, 8, 15, 16, 23, 42]

Then write fib : Nat -> Nat with the patterns 0, 1 and n + 2, where the last case returns fib n + fib (n + 1), and check that #eval fib 10 prints 55.

Sources

Try it yourselfMedium

Write recursion Lean can see will stop

Write `digits`, the number of decimal digits of a natural number (count 0 as 1 digit). The recursive call is on `n / 10`, which is not a structural sub-term, so you must show Lean it gets smaller with a `termination_by` and `decreasing_by` clause. A hint for the last part: `omega` proves simple facts about natural number arithmetic, including division by a constant. Until you fill in the sorry holes, the #eval lines show an error saying the expression depends on sorry; that is expected.

def digits (n : Nat) : Nat :=
  if h : n < 10 then 1 else 1 + digits (n / 10)
termination_by n
decreasing_by
  sorry

#eval digits 0      -- 1
#eval digits 2026   -- 4
Open in the Lean web editor

The official Lean editor runs in your browser and checks the file on Lean's server. Replace every sorry until no errors or warnings are left, then mark it solved.

The worked solution unlocks after your first attempt.

Saved in this browser. Pass the quiz while signed in to count it for the certificate.

Check what you learned

Answer all 3 questions. You need at least 2 right to pass.

1. Why does Lean require ordinary functions to terminate?

2. Why is factorial with patterns 0 and n + 1 accepted automatically?

3. What is the cost of marking a function partial?