Created
July 7, 2024 12:20
-
-
Save espio999/18316a346782f4243f077f3d86a8f8e4 to your computer and use it in GitHub Desktop.
F# fibonacci 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 rec fib n = | |
match n with | |
| 0 | 1 -> n | |
| n -> fib (n-1) + fib (n-2) | |
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