Recursion
Recursion is Lean's core looping mechanism. If you can define a function by structural recursion, Lean guarantees it terminates.
Recursive Functions on Nat
lean
1def factorial : Nat → Nat2 | 0 => 13 | n + 1 => (n + 1) * factorial n45#eval factorial 5Recursive Functions on Lists
Lists are recursive by nature, so many functions mirror the structure of the list.
lean
1def sumList : List Nat → Nat2 | [] => 03 | x :: xs => x + sumList xs45#eval sumList [1, 2, 3]Exercise: Count Elements
Write a function that returns the length of a list of strings.
lean
1def countStrings : List String → Nat2 | [] => 03 | _ :: xs => 1 + countStrings xsℹ
Lean enforces termination. If your recursion is not obviously structural, you will need a termination argument (covered later).
Key Takeaway
Recursion is the idiomatic way to loop in Lean. Structural recursion gives you free termination guarantees.