I am trying to learn Python, and although I am enthusiastic about closing in Python, I am having trouble getting the code to work correctly:
def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x<2: return x return fib(x-1)+fib(x-2) def fibm(x): if x<2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm)
Basically, what this should do is use closure to maintain the function state stored in memory. I understand that it is probably much faster, easier to read, and generally more โPutin'sโ ways to realize this; however, my goal is to understand how Python closures work and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code does not work and what I can do (if anything) to fix it.
The problem I am facing is when I try to use fibm - Python insists that get not defined:
Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import memoize >>> memoize.fibm(35) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined >>>
Seeing that I'm new to Python, I donโt know if I did something wrong or is it just a language restriction. I hope this is the first. :-)
Kyle cronin
source share