A memoization function.
local Memoize = require 'knife.memoize'
Memoize a function.
-
function func
Function to memoize.
- Memoized function.
function fibonacci (n)
return n < 2 and n or fibonacci(n - 1) + fibonacci(n - 2)
end
fibonacci = Memoize(fibonacci)
-
For background information on memoization, see kikito/memoize.
-
Unlike other popular implementations, this memoize function accepts nil values in arguments lists as well as in return values.
-
This implementation uses weak tables when caching results. If a table is passed to a memoized function and at some point nothing references that table, the associated cached result may be cleared. This makes sense since a cached result is not retrievable once an argument associated with it no longer exists.