Add func.memoize

master
Lars Mueller 2022-01-18 18:47:38 +01:00
parent 479afb6c88
commit f4b7eca18f
2 changed files with 26 additions and 2 deletions

View File

@ -1,6 +1,6 @@
-- Localize globals
local error, coroutine, math, modlib, unpack
= error, coroutine, math, modlib, unpack
local error, coroutine, math, modlib, unpack, select, setmetatable
= error, coroutine, math, modlib, unpack, select, setmetatable
-- Set environment
local _ENV = {}
@ -35,6 +35,20 @@ function values(...)
return function() return unpack(args) end
end
function memoize(func)
return setmetatable({}, {
__index = function(self, key)
local value = func(key)
self[key] = value
return value
end,
__call = function(self, arg)
return self[arg]
end,
__mode = "k"
})
end
-- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
function iterate(callback, iterator, state, ...)
local function loop(...)

View File

@ -53,6 +53,16 @@ do
end
assert(next(tab) == nil)
assert(func.aggregate(func.add, 1, 2, 3) == 6)
local called = false
local function fun(arg)
assert(arg == "test")
local retval = called
called = true
return retval
end
local memo = func.memoize(fun)
assert(memo(arg) == false)
assert(memo(arg) == false)
end
-- string