How do I write a generic memoize function?

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

    I've been inspired by this question to implement (yet another) flexible memoize function in Lua.

    https://github.com/kikito/memoize.lua

    Main advantages:

    • Accepts a variable number of arguments
    • Doesn't use tostring; instead, it organizes the cache in a tree structure, using the parameters to traverse it.
    • Works just fine with functions that return multiple values.

    Pasting the code here as reference:

    local globalCache = {}
    
    local function getFromCache(cache, args)
      local node = cache
      for i=1, #args do
        if not node.children then return {} end
        node = node.children[args[i]]
        if not node then return {} end
      end
      return node.results
    end
    
    local function insertInCache(cache, args, results)
      local arg
      local node = cache
      for i=1, #args do
        arg = args[i]
        node.children = node.children or {}
        node.children[arg] = node.children[arg] or {}
        node = node.children[arg]
      end
      node.results = results
    end
    
    
    -- public function
    
    local function memoize(f)
      globalCache[f] = { results = {} }
      return function (...)
        local results = getFromCache( globalCache[f], {...} )
    
        if #results == 0 then
          results = { f(...) }
          insertInCache(globalCache[f], {...}, results)
        end
    
        return unpack(results)
      end
    end
    
    return memoize
    

提交回复
热议问题