Skip to content

Instantly share code, notes, and snippets.

@espio999
Created July 6, 2024 14:11
Show Gist options
  • Save espio999/f8ba9b70a72f1cb61dc10f8d11624a38 to your computer and use it in GitHub Desktop.
Save espio999/f8ba9b70a72f1cb61dc10f8d11624a38 to your computer and use it in GitHub Desktop.
F# 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 square n =
printfn "computing square of %d" n
printfn "%A" <| (n * n)
let memSquare = memoize square
memSquare 42
memSquare 42
memSquare 99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment