memoize.lua
Re: memoize.lua
Ok, that makes sense. Thanks
- kikito
- Inner party member
- Posts: 3153
- Joined: Sat Oct 03, 2009 5:22 pm
- Location: Madrid, Spain
- Contact:
Re: memoize.lua
I've made two changes in memoize.lua:
- It now supports funcTables and functions. It'll throw an error if you try to memoize anything else. The cache is reset if the __call function of a funcTable changes
- I've explicitly tested and documented that you can erase a function's cache by re-memoizing
When I write def I mean function.
Re: memoize.lua
I wanted a small memoize function that could support nil arguments and expose the cache. Here's what I came up with, maybe it will be useful for someone else:
It doesn't check for user error, including changes to __call on functables. Memoizing a function again doesn't clear the cache. Other than that, it should work the same (passes relevant parts of this spec).
I threw it in a gist here, along with another longer version that passes the rest of this spec and also supports nil arguments.
Code: Select all
local function memoize (f)
local cache = setmetatable({}, { __mode = 'k' })
local resultsKey = {}
local nilKey = {}
return function (...)
local args = { ... }
local node = cache
for i = 1, #args do
local key = args[i]
if key == nil then
key = nilKey
end
if not node[key] then
node[key] = setmetatable({}, { __mode = 'k' })
end
node = node[key]
end
if not node[resultsKey] then
node[resultsKey] = { f(...) }
end
return unpack(node[resultsKey])
end, cache, resultsKey, nilKey
end
I threw it in a gist here, along with another longer version that passes the rest of this spec and also supports nil arguments.
Last edited by airstruck on Tue Jun 16, 2015 9:34 pm, edited 1 time in total.
- Robin
- The Omniscient
- Posts: 6506
- Joined: Fri Feb 20, 2009 4:29 pm
- Location: The Netherlands
- Contact:
Re: memoize.lua
Code: Select all
local key = args[i] or nilKey
Help us help you: attach a .love.
Re: memoize.lua
Robin wrote:Also uses nilKey if args == false.
Ahh yeah, good catch. Fixed.
Re: memoize.lua
Testing with luajit exposed some problems with sparse arrays that didn't appear under regular Lua. An up-to-date version of a memoize function handling nil arguments and return values and meeting kikito's spec is here: https://github.com/airstruck/knife/blob ... emoize.lua
Who is online
Users browsing this forum: No registered users and 14 guests