How do I write a generic memoize function?

后端 未结 15 1720
情话喂你
情话喂你 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:12

    function memoize (f)
       local cache = {}
       return function (x)
                 if cache[x] then
                    return cache[x]
                 else
                    local y = f(x)
                    cache[x] = y
                    return y
                 end
              end
    end
    
    triangle = memoize(triangle);
    

    Note that to avoid a stack overflow, triangle would still need to be seeded.

提交回复
热议问题