Memoization having a pure function (not just of type unit -> 'a
, but any other too) as a lookup key is impossible because functions in general do not have equality comparer for the reason.
It may seem that for this specific type of function unit -> 'a
it would be possible coming up with a custom equality comparer. But the only approach for implementing such comparer beyond extremes (reflection, IL, etc.) would be invoking the lookup function as f1 = f2 iff f1() = f2()
, which apparently nullifies any performance improvement expected from memoization.
So, perhaps, as it was already noted, for this case optimizations should be built around lazy
pattern, but not memoization
one.
UPDATE: Indeed, after second look at the question all talking above about functions missing equality comparer is correct, but not applicable, because memoization happens within each function's individual cache
from the closure. On the other side, for this specific kind of functions with signature unit->'a
, i.e. at most single value of argument, using Dictionary
with most one entry is an overkill. The following similarly stateful, but simpler implementation with just one memoized value will do:
let memoize2 f =
let notFilled = ref true
let cache = ref Unchecked.defaultof<'a>
fun () ->
if !notFilled then
cache := f ()
notFilled := false
!cache
used as let foo = memoize2(fun () -> ...heavy on time and/or space calculation...)
with first use foo()
performing and storing the result of calculation and all successive foo()
just reusing the stored value.
Lazy
is the right tool in this case. – Incendiarismlazy
, something like this:let memoize f = let result = lazy (f()) in fun () -> result.Value
– Incendiarism