This memoize function fails on any functions of type () -> 'a at runtime with a Null-Argument-Exception.
let memoize f =
let cache = System.Collections.Generic.Dictionary()
fun x ->
if cache.ContainsKey(x) then
cache.[x]
else
let res = f x
cache.[x] <- res
res
Is there a way to write a memoize function that also works for a () -> 'a ?
(My only alternative for now is using a Lazy type. calling x.Force() to get the value.)
The reason why the function fails is that F# represents unit
()usingnullof typeunit. The dictionary does not allow takingnullvalues as keys and so it fails.In your specific case, there is not much point in memoizing function of type
unit -> 'a(because it is better to uselazyfor this), but there are other cases where this would be an issue - for exampleNoneis also represented bynullso this fails too:The easy way to fix this is to wrap the key in another data type to make sure it is never
null:Then you can just wrap the key with the
Kconstructor and everything will work nicely: