I wrote code to (naively) perform automatic memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.
My Code
def naive_memoise(caches):
def memoise(f):
nonlocal caches
def mem_f(n):
nonlocal caches, f
if f not in caches:
caches[f] = {}
if n not in caches[f]:
caches[f][n] = f(n)
return caches[f][n]
return mem_f
return memoise
Sample Usage
def fib(n):
if n in [0, 1]:
return n
return fib(n - 2) + fib(n - 1)
mem = naive_memoise({})
fib = mem(fib)