[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Soliciting criticism of memoize function
- From: nr@... (Norman Ramsey)
- Date: Wed, 14 May 2008 21:40:15 -0400 (EDT)
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