Functions
Functions are the heart of Lean. Learn to define them with explicit types and use pattern matching to make them expressive.
Definitions with def
lean
1def add (x : Nat) (y : Nat) : Nat := x + y2#eval add 3 534def greet (name : String) : String := "Hello, " ++ name5#eval greet "Lean"Pattern Matching
Lean uses match to branch on values.
lean
1def isZero (n : Nat) : Bool :=2 match n with3 | 0 => true4 | _ => false56#eval isZero 07#eval isZero 4Exercise: Option Defaults
Define a function that extracts a value from Option Nat and returns a default when it is none.
lean
1def getOrZero (value : Option Nat) : Nat :=2 match value with3 | some n => n4 | none => 056#eval getOrZero (some 7)7#eval getOrZero none💡
Lean encourages small, pure functions. Keep them focused and let the types guide you.
Key Takeaway
Functions in Lean are pure by default. Pattern matching is the standard way to branch on data.