Home
Insert
Update snippet 'memoizeBy'
Title
Passcode
Description
Sometimes you might wish to memoize a function whose input doesn't have the equality and comparison constraints, or maybe the comparison of your given type is just too slow for what you need. To fix this, you simply provide a function which converts the input into something more fitting as an extra parameter.
Source code
// Note that Dictionary lookups are to be much faster than F#'s map and so should // be used when writing library code. let memoizeBy inputToKey f = let cache = Dictionary<_, _>() fun x -> let k = inputToKey x if cache.ContainsKey(k) then cache.[k] else let res = f x cache.[k] <- res res // Example: open System /// a cached version of Type.GetGenericArguments() let cachedGetGenericArguments : Type -> Type[] = memoizeBy (fun t -> t.FullName) (fun t -> t.GetGenericArguments())
Tags
memoize
memoization
functions
utility
memoize
memoization
functions
utility
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update