有没有办法可以在函数内本地化记忆(通过 Memoize.jl)?或者至少删除通过记忆创建的词典?
澄清:假设我定义了一个定义函数 f(x, y)。我想为 y 的每个新值创建一个新表。也就是说,给定 y = y0,f( . , y0) 对 x、x-1 等进行自身迭代,但给定一个新的 y = y1,我不需要为 y0 存储旧表,这样内存就可以被释放。我怎样才能做到这一点?
解决方案:
cachedfib() = begin
global dict = Dict()
global dict2 = Dict()
function _fib(n::Int, a::Int)
if !haskey(dict2, a)
dict2[a] = true
dict = Dict()
end
if haskey(dict, (n, a))
return dict[(n, a)]
elseif n < 2
dict[(0, a)] = 0
dict[(1, a)] = 1
return dict[(n, a)]
else
dict[(n, a)] = a*(_fib(n - 1, a) + _fib(n - 2, a))
return dict[(n, a)]
end
end
end
fib = cachedfib()
fib(10, 1)
fib(10, 2)
Run Code Online (Sandbox Code Playgroud)
现在调用dict并dict2检查字典是否在每次第二个参数更改时刷新。当要存储的参数是整数并且您使用Array而不是Dict
要使用记忆技术,您可以使用 或 闭包来完成let。看看我的快速实现factorial(带关闭)。
with_cached_factorial() = begin
local _cache = [1] #cache factorial(0)=1
function _factorial(n)
if n < length(_cache)
println("pull out from the cache factorial($n)=$(_cache[n+1])")
_cache[n+1]
else
fres = n * _factorial(n-1)
push!(_cache, fres)
println("put factorial($n)=$fres into the cache of the size=$(sizeof(_cache))") #a
fres
end
end
end
Run Code Online (Sandbox Code Playgroud)
现在,只需使用它:
julia> myf = with_cached_factorial()
_factorial (generic function with 1 method)
julia> myf(3)
pull out from the cache factorial(0)=1
put factorial(1)=1 into the cache of the size=16
put factorial(2)=2 into the cache of the size=24
put factorial(3)=6 into the cache of the size=32
6
julia> myf(5)
pull out from the cache factorial(3)=6
put factorial(4)=24 into the cache of the size=40
put factorial(5)=120 into the cache of the size=48
120
julia> myf(10)
pull out from the cache factorial(5)=120
put factorial(6)=720 into the cache of the size=56
put factorial(7)=5040 into the cache of the size=64
put factorial(8)=40320 into the cache of the size=72
put factorial(9)=362880 into the cache of the size=80
put factorial(10)=3628800 into the cache of the size=88
3628800
Run Code Online (Sandbox Code Playgroud)