Skip to content

Instantly share code, notes, and snippets.

@espio999
Created July 7, 2024 12:20
Show Gist options
  • Save espio999/18316a346782f4243f077f3d86a8f8e4 to your computer and use it in GitHub Desktop.
Save espio999/18316a346782f4243f077f3d86a8f8e4 to your computer and use it in GitHub Desktop.
F# fibonacci with memoize
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