Created
July 7, 2024 12:20
-
-
Save espio999/6a34a0ec39d0da64bf3f6e17d0de8771 to your computer and use it in GitHub Desktop.
F# fibonacci in tail recursion with memoize
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
let memoize fn = | |
let cache = new System.Collections.Generic.Dictionary<_,_>() | |
printfn "counter: %A" cache.Count | |
fun x -> | |
printfn "%A is received" x | |
match cache.TryGetValue x with | |
| true, v -> v | |
| false, _ -> let v = fn (x) | |
cache.Add(x,v) | |
v | |
let fib n = | |
let rec loop acc1 acc2 n = | |
match n with | |
| 0 -> acc1 | |
| 1 -> acc2 | |
| _ -> loop acc2 (acc1 + acc2) (n - 1) | |
loop 0 1 n | |
let memo_fib = memoize fib | |
let sw = new System.Diagnostics.Stopwatch() | |
sw.Start() | |
memo_fib 45 |> printfn "%A" | |
sw.ToString() |> printfn "%s" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment