-
-
Save jasonrute/dfc817b1a3e175bd51b3acaaf7cf9613 to your computer and use it in GitHub Desktop.
Memoized fibonacci #lean #lean4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- lean4 | |
import Std.Data.HashMap | |
structure FibCache where | |
cache : Std.HashMap Nat Nat := {} | |
def fibMemoized : Nat → (StateM FibCache Nat) | |
| 0 => pure 0 | |
| 1 => pure 1 | |
| n+2 => do | |
-- first check cache | |
match (← get).cache.find? (n+2) with | |
| some f => pure f | |
| none => | |
--dbgTrace! s!"Computing fib {n+2}" | |
let f2 ← fibMemoized (n+1) | |
let f1 ← fibMemoized n | |
let f := f1 + f2 | |
modify <| fun state => { cache := state.cache.insert (n+2) f : FibCache } | |
pure f | |
def fib (n : Nat) : Nat := (fibMemoized n).run' {} | |
/- Sum of first n fibonacci numbers -/ | |
def fibSumAux (n : Nat) : StateM FibCache Nat := do | |
let mut s := 0 | |
for i in [0:n] do | |
s := s + (← fibMemoized i) | |
return s | |
def fibSum (n : Nat) : Nat := (fibSumAux n).run' {} | |
#eval fib 1000 | |
#eval fibSum 1000 |
Replaced get...set
with modify
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I fixed a left over line of code and removed the
partial
.