lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Is there anything wrong with the following:

local function memoize(f)
    local function index(t, x)
        local v = f(x)
        t[x] = v
        return v
    end

    local cache = setmetatable({}, {__mode = 'k', __index = index})

    return function(x)
        return cache[x]
    end
end


On May 14, 2008, at 6:40 PM, Norman Ramsey wrote:

I would be pleased if readers of this list could think of any improvements
to the following memoize function:

  function memoize (f)
    -- f must take at most one argument and return at most one result
      local cache = setmetatable({ }, { __mode = 'k' })
      local function update(x, v, ...) -- f(x) returns v, ...
        assert(select('#', ...) == 0)
        cache[x] = v
        return v
      end

      return function (x, ...)
assert(select('#', ...) == 0) -- cache works with at most one arg
               local v = cache[x]
               if v ~= nil then
                 return v
               else
                 return update(x, f(x))
               end
             end
  end

I'm especially concerned whether I have the cache's __mode metamethod
set correctly, as I always get confused about the semantics of weak
keys and weak values.


Norman

--
Gé Weijers
ge@weijers.org