Pattern Matching
Pattern matching is the cleanest way to deconstruct data and express branching logic in Lean. It is essential for recursion and proofs.
Matching on Nat
lean
1def describe (n : Nat) : String :=2 match n with3 | 0 => "zero"4 | 1 => "one"5 | _ => "many"67#eval describe 08#eval describe 5Matching on Option
Option types require you to handle some and none.
lean
1def showOption (value : Option String) : String :=2 match value with3 | some name => s!"Hello {name}"4 | none => "No name"56#eval showOption (some "Lean")7#eval showOption noneExercise: Match on Lists
Write a function that returns the first element of a list or noneif the list is empty.
lean
1def headOption (xs : List Nat) : Option Nat :=2 match xs with3 | [] => none4 | x :: _ => some x💡
Pattern matching keeps your code total: you must cover every case.
Key Takeaway
Pattern matching is Lean's go-to tool for branching logic and data deconstruction.