Created
July 6, 2024 14:11
-
-
Save espio999/f8ba9b70a72f1cb61dc10f8d11624a38 to your computer and use it in GitHub Desktop.
F# 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 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