How do I write a generic memoize function?

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

    I bet something like this should work with variable argument lists in Lua:

    local function varg_tostring(...)
        local s = select(1, ...)
        for n = 2, select('#', ...) do
            s = s..","..select(n,...)
        end
        return s
    end
    
    local function memoize(f)
        local cache = {}
        return function (...)
            local al = varg_tostring(...)
            if cache[al] then
                return cache[al]
            else
                local y = f(...)
                cache[al] = y
                return y
            end
        end
    end
    

    You could probably also do something clever with a metatables with __tostring so that the argument list could just be converted with a tostring(). Oh the possibilities.

提交回复
热议问题