Memoize decorators failing to memoize (when not using decorator syntax)

送分小仙女□ 提交于 2019-12-08 06:46:31

There is nothing curious about this. When you do

memofib = funcmemo(fib)

You're not changing the function fib points to in any way, but creating a new function and pointing the name memofib at it.

So when memofib gets called, it calls the function pointed to by the name fib -- which recursively calls itself, not memofib -- so no memoization occurs.

In your second example, you do

fib = funcmemo(fib)

so it calls itself recursively and memoization happens at all levels.

If you don't want to overwrite the name fib, as the decorator version or your second example does, you could alter fib to take a function name:

def fib(n, fibfunc):
    print "fib called with:", n
    if n < 2: return n
    return fibfunc(n-2, fibfunc) + fibfunc(n-1, fibfunc)

memofib = funcmemo(fib)
res = fib(3, memofib)

You could also use a fixed point combinator to avoid passing fibfunc every time:

def Y(f):
    def Yf(*args):
        return f(Yf)(*args)
    return f(Yf)

@Y
def fib(f):
    def inner_fib(n):
        print "fib called with:", n
        if n < 2: return n
        return f(n-2) + f(n-1)
    return inner_fib

In case your question is just a simple why, I guess the answer is just because the recursion-call with fib() does call the function with the name fib(). To decorate that you have to replace the value of the pointer fib; this is not done by memfib = funcmemo(fib) nor by the class version.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!