Created
July 23, 2024 15:20
-
-
Save espio999/d2a9d19d20c8feb0cc83bd8319cb68e2 to your computer and use it in GitHub Desktop.
F# memoization module
This file contains hidden or 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
module memoization | |
open System.Collections.Generic | |
open System.Collections.Concurrent | |
let memoization fn = | |
let cache = new Dictionary<_,_>() | |
printfn "counter: %A" cache.Count | |
fun arg -> | |
printfn "%A is received" arg | |
match cache.TryGetValue arg with | |
| true, value -> value | |
| false, _ -> | |
let value = fn arg | |
cache.Add(arg, value) | |
value | |
let thread_safe_memoization fn = | |
let cache = new ConcurrentDictionary<_,_>() | |
printfn "counter: %A" cache.Count | |
fun arg -> | |
printfn "%A is received" arg | |
match cache.TryGetValue arg with | |
| true, value -> value | |
| false, _ -> | |
let value = lazy fn arg | |
cache.TryAdd(arg, value.Force()) |> ignore | |
value.Force() | |
let shorter_memoization fn = | |
let cache = new ConcurrentDictionary<_,_>() | |
fun arg -> cache.GetOrAdd(arg, lazy fn arg).Value | |
let memoization_2args fn = shorter_memoization (fun (arg1, arg2) -> fn arg1 arg2) |> fun fn' arg1 arg2 -> fn' (arg1, arg2) | |
let memoization_3args fn = shorter_memoization (fun (arg1, arg2, arg3) -> fn arg1 arg2 arg3) |> fun fn' arg1 arg2 arg3 -> fn' (arg1, arg2, arg3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment