Created
August 14, 2012 17:01
-
-
Save toivoh/3350871 to your computer and use it in GitHub Desktop.
@memoized macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro expect(pred) | |
:( ($esc(pred)) ? nothing : error($"error: expected $pred == true") ) | |
end | |
is_expr(ex, head::Symbol) = (isa(ex, Expr) && (ex.head == head)) | |
function split_fdef(fdef::Expr) | |
@expect (fdef.head == :function) || (fdef.head == :(=)) | |
@expect length(fdef.args) == 2 | |
signature, body = tuple(fdef.args...) | |
@expect is_expr(signature, :call) | |
@expect length(signature.args) >= 1 | |
(signature, body) | |
end | |
split_fdef(f::Any) = error("split_fdef: expected function definition, got\n$f") | |
macro memoized(fdef) | |
code_memoized(fdef) | |
end | |
function code_memoized(fdef) | |
signature, body = split_fdef(fdef) | |
args = signature.args[2:end] | |
memo = expr(:quote, ObjectIdDict()) | |
expr(:function, esc(signature), quote | |
key = ($esc(expr(:tuple, args))) | |
has(($memo), key) ? ($memo)[key] : | |
(($memo)[key] = let; ($esc(body)); end) | |
end) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Test | |
import Base.* | |
load("memoized.jl") | |
ex = code_memoized(:(f(x) = randi())) | |
println(ex) | |
@memoized f(x) = return randi(10) | |
println() | |
println({f(x) for x=1:10}) | |
println({f(x) for x=1:10}) | |
@memoized fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) | |
println() | |
@time fib(20) | |
@time fib(20) | |
end |
Your're right. Thanks!
Ok, added a let block to fix it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think this handles
return
in the body, since that will cause the whole function to return without modifying the dictionary.