How do I write a generic memoize function?

后端 未结 15 1704
情话喂你
情话喂你 2020-12-09 05:25

I\'m writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   retu         


        
15条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 06:18

    Extending the idea, it's also possible to memoize functions with two input parameters:

    function memoize2 (f)
       local cache = {}
       return function (x, y)
                 if cache[x..','..y] then
                    return cache[x..','..y]
                 else
                    local z = f(x,y)
                    cache[x..','..y] = z
                    return z
                 end
              end
    end
    

    Notice that parameter order matters in the caching algorithm, so if parameter order doesn't matter in the functions to be memoized the odds of getting a cache hit would be increased by sorting the parameters before checking the cache.

    But it's important to note that some functions can't be profitably memoized. I wrote memoize2 to see if the recursive Euclidean algorithm for finding the greatest common divisor could be sped up.

    function gcd (a, b) 
       if b == 0 then return a end
       return gcd(b, a%b)
    end
    

    As it turns out, gcd doesn't respond well to memoization. The calculation it does is far less expensive than the caching algorithm. Ever for large numbers, it terminates fairly quickly. After a while, the cache grows very large. This algorithm is probably as fast as it can be.

提交回复
热议问题