Add func.memoize

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

@ -1,6 +1,6 @@
-- Localize globals -- Localize globals
local error, coroutine, math, modlib, unpack local error, coroutine, math, modlib, unpack, select, setmetatable
= error, coroutine, math, modlib, unpack = error, coroutine, math, modlib, unpack, select, setmetatable
-- Set environment -- Set environment
local _ENV = {} local _ENV = {}
@ -35,6 +35,20 @@ function values(...)
return function() return unpack(args) end return function() return unpack(args) end
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` -- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
function iterate(callback, iterator, state, ...) function iterate(callback, iterator, state, ...)
local function loop(...) local function loop(...)

@ -53,6 +53,16 @@ do
end end
assert(next(tab) == nil) assert(next(tab) == nil)
assert(func.aggregate(func.add, 1, 2, 3) == 6) 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 end
-- string -- string