Example Worked Example: Memoized Fibonacci Footprint
example formalized

Worked Example: Memoized Fibonacci Footprint

Fibonacci instrumented in CostM (Visited ℕ) (Memoization Footprint via the Visited Monoid), so the cost field records the set of indices the recursion touches rather than a call count. Because the Visited monoid is idempotent, the footprint collapses to the distinct subproblems: $$ (\operatorname{fib} n).\mathrm{cost}.\mathrm{toFinset} \;=\; \{0, 1, \dots, n\} \;=\; \operatorname{range}(n+1), $$ hence fib_cost_card : (fib n).cost.toFinset.card = n + 1 — exactly n+1 distinct subproblems, the hallmark of an O(n) memoized DP.

Correctness and cost are proved independently: fib_value : (fib n).ret = Nat.fib n lives on .ret, while fib_cost lives on .cost. This is the intended CostM separation (The CostM Complexity Monad).

Lean declarations

  • MemoFib.fibAux, MemoFib.fib — the instrumented recursion and its wrapper.
  • MemoFib.fibAux_ret, MemoFib.fib_value — correctness (= Nat.fib).
  • MemoFib.fibAux_cost, MemoFib.fib_cost, MemoFib.fib_cost_card — the footprint equals range (n+1), of cardinality n+1.

References

Also in