Skip to content

Instantly share code, notes, and snippets.

@lamg
Created November 4, 2026 11:38
Show Gist options
  • Select an option

  • Save lamg/4fa9500f99f0e95c77e73d23cded04cd to your computer and use it in GitHub Desktop.

Select an option

Save lamg/4fa9500f99f0e95c77e73d23cded04cd to your computer and use it in GitHub Desktop.
Iterative and recursive Fibonacci have the same result
def fibonacci_rec
| 0 => 1
| 1 => 1
| Nat.succ n => fibonacci_rec n + fibonacci_rec (n - 1)
def fibonacci_iter (n: Nat) :=
let step := fun _ _ (fibₙ, «fibₙ₊₁») => («fibₙ₊₁», fibₙ + «fibₙ₊₁»)
(n.fold step (1,1))
#eval (List.range 7).map fibonacci_rec
-- [1, 1, 2, 3, 5, 8, 13]
#eval (List.range 7).map (fun n => (fibonacci_iter n).1)
-- [1, 1, 2, 3, 5, 8, 13]
theorem fibonacci_iter_eq_rec:
∀ n, fibonacci_iter n = (fibonacci_rec n, fibonacci_rec (n+1))
:= by
intro n
induction n with
| zero => simp[fibonacci_iter, fibonacci_rec]
| succ n ih =>
simp [fibonacci_iter]
simp [fibonacci_iter] at ih
rw [ih]
simp [fibonacci_rec, Nat.add_comm (fibonacci_rec n)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment