Skip to content
LeanLearn
Level 2~25 minLean 4

Recursion: functions that use themselves

Watch a computer unfold recursive calls step by step, see the call stack grow and shrink, and learn why Lean insists that every recursion ends.

You will be able to
  • Identify the base case and the recursive case of a definition.
  • Trace a recursive computation and predict its result.
  • Explain why recursion must make progress towards the base case, and how Lean checks this.

Recommended first: Meet Lean: evaluate, check, define. You can start anyway. Nothing is locked.

EncounterActivity 1 of 9

Encounter

How many dolls are inside a set of nesting dolls? A simple rule answers it:

  • If the doll is solid (nothing inside), the answer is 1. This is the base case.
  • Otherwise, the answer is 1 + (the number of dolls inside the next doll). This is the recursive case: the rule uses itself, but on a smaller doll.

Factorial works the same way: 0!=10! = 1, and (n+1)!=(n+1)×n!(n+1)! = (n+1) \times n!. In Lean:

def fact : Nat → Nat
  | 0 => 1
  | n + 1 => (n + 1) * fact n