Created
December 14, 2012 09:07
-
-
Save toivoh/4283893 to your computer and use it in GitHub Desktop.
@get! macro
This file contains hidden or 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
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 |
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from
test.jl
: