
Jacek Generowicz
def memoize(fn): cache = {} def memoized_fn(*args): if args not in cache: cache[args] = fn(*args) return cache[args] return memoized_fn
Here's a simplified memoizer for Haskell: memoize :: (Integral t) => (t -> a) -> t -> a memoize f = ([f i | i <- [0..]]!!) . fromIntegral
But what should the type of fn be? What should the type of args be?
The args to fn must be of a type that is indexable by the memoizing structure. My example is simplistic, and will only memoize functions where the first argument is a integral, non-negative number, and it uses a list (with O(n) access), but you can probably improve it as you see fit. I think this will work for multi-parameter functions too, because of currying.
In Python, I don't care, as long no type error occurs when they are combined thus:
fn(*args)
In Haskell, the type of 'memoize g' is the same as 'g', so you don't have to care - the compiler cares for you. :-) Perhaps I'm missing something obvious? -k -- If I haven't seen further, it is by standing in the footprints of giants