Skip to content

Instantly share code, notes, and snippets.

@toivoh
Created December 14, 2012 09:07
Show Gist options
  • Save toivoh/4283893 to your computer and use it in GitHub Desktop.
Save toivoh/4283893 to your computer and use it in GitHub Desktop.
@get! macro
is_expr(ex, head::Symbol) = (isa(ex, Expr) && (ex.head == head))
is_expr(ex, head::Symbol, n::Int) = is_expr(ex, head) && length(ex.args) == n
# simple syntax version
macro get!(d, k, default)
quote
d, k = $(esc(d)), $(esc(k))
has(d, k) ? d[k] : (d[k] = $(esc(default)))
end
end
# fancy syntax version, probably puts too much emphasis on assignment
macro get2!(ex)
if !is_expr(ex, :(=), 2); error("@setdefault: not an assignment"); end
lhs, default = ex.args
if !is_expr(lhs, :ref, 2); error("@setdefault: single index expected"); end
d, k = lhs.args
quote
d, k = $(esc(d)), $(esc(k))
has(d, k) ? d[k] : (d[k] = $(esc(default)))
end
end
d = {19=>2}
@show d
@show @get!(d, 8, 19)
@show @get!(d, 19, 7)
@show d
println()
d2 = {19=>2}
@show d2
@show (@get2! d2[8] = 19)
@show (@get2! d2[19] = 7)
@show d2
@toivoh
Copy link
Author

toivoh commented Dec 14, 2012

Output from test.jl:

d   = {19=>2}
@get! d 8 19    = 19
@get! d 19 7    = 2
d   = {8=>19,19=>2}

d2  = {19=>2}
@get2! d2[8] = 19    = 19
@get2! d2[19] = 7    = 2
d2  = {8=>19,19=>2}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment