Skip to content

Instantly share code, notes, and snippets.

@kmsquire
Created May 16, 2013 12:57
Show Gist options
  • Save kmsquire/5591523 to your computer and use it in GitHub Desktop.
Save kmsquire/5591523 to your computer and use it in GitHub Desktop.
Alternate version of memoized.jl
macro memoize(ex)
local f, u, g
g = randstring(6)
if isa(ex,Expr) && (ex.head == :function || ex.head == symbol("=")) &&
!isempty(ex.args) && ex.args[1].head == :call && !isempty(ex.args[1].args)
f = ex.args[1].args[1]
ex.args[1].args[1] = u = symbol(string(f,"_unmemoized"))
else
error("@memoize must be applied to a method definition")
end
f_cache = esc(symbol(string(f,"_cache_$g")))
quote
$(esc(ex))
const ($f_cache) = (Tuple=>Any)[]
$(esc(f))(args...) = has(($f_cache),args) ?
($f_cache)[args] : (($f_cache)[args] = $(esc(u))(args...))
end
end
macro unmemoize(ex)
local f, u
if isa(ex,Expr) && (ex.head == :function || ex.head == symbol("=")) &&
!isempty(ex.args) && ex.args[1].head == :call && !isempty(ex.args[1].args)
f = ex.args[1].args[1]
ex.args[1].args[1] = u = symbol(string(f,"_unmemoized"))
else
error("@unmemoize must be applied to a method definition")
end
quote
$(esc(ex))
$(esc(f))(args...) = $(esc(u))(args...)
end
end
macro memofixed(default, ex)
local f, g
g = randstring(6)
if isa(ex,Expr) && (ex.head == :function || ex.head == symbol("=")) &&
!isempty(ex.args) && ex.args[1].head == :call && !isempty(ex.args[1].args)
f = ex.args[1].args[1]
ex.args[1].args[1] = u = symbol(string(f,"_unmemoized"))
eval(expr(:export, u))
else
error("@memofixed must be applied to a method definition")
end
f_cache = esc(symbol(string(f,"_cache_$g")))
quote
$(esc(ex))
const ($f_cache) = (Tuple=>Any)[]
function $(esc(f))(args...)
if has(($f_cache),args)
($f_cache)[args]
else
($f_cache)[args] = base_val = $(expr(:call, default, expr(:..., :args)))
ret_val = $(esc(u))(args...)
if ret_val != base_val
for i = 1:100
($f_cache)[args] = base_val = ret_val
ret_val = $(esc(u))(args...)
if ret_val == base_val break end
end
if ret_val != base_val
error("Could not find fixed point of ",($f),"$args in 100 iterations of $u")
end
end
ret_val
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment