This library encourages you to do memoization in three separate steps:
Create a memoizable function
Create or select an appropriate memoizer
Run the memoizer on the memoizable function
Let's start with the first.
When you create a memoizable function,
you should use the
which is that the first input to the function is
and all recursive calls are replaced with
One common convention that goes well with the
is using a helper function
go, like so:
fib :: Memoizable (Integer -> Integer) fib self = go where go 0 = 1 go 1 = 1 go n = self (n-1) + self (n-2)
Now for the second. For this example,
we need a Memoizer that can handle an
integral, which handles any
Integral input, and
which can memoize any function
a -> b, given an
Third, let's run our memoizers! Since we have decoupled the definition of the memoized function from its actual memoization, we can create multiple memoized versions of the same function if we so desire.
import qualified Data.MemoUgly as Ugly import qualified Data.MemoCombinators as MC fibUgly :: Integer -> Integer fibUgly = runMemo Ugly.memo fib fibMC :: Integer -> Integer fibMC = runMemo MC.integral fib
You could easily do the same with
Using this technique, you can create local memoized functions whose memo tables are garbage collected as soon as they are no longer needed.