Created
June 20, 2014 19:39
-
-
Save siddMahen/d491c5c848e705401607 to your computer and use it in GitHub Desktop.
Turns a literal dictionary into an array of tuples.
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 ordered(ex::Expr) | |
if ex.head == :dict | |
ex.head = :vcat | |
ex.args = map(ex.args) do x | |
:(($(esc(x.args[1])),$(esc(x.args[2])))) | |
end | |
elseif ex.head == :typed_dict | |
ex.head = :vcat | |
shift!(ex.args) | |
ex.args = map(ex.args) do x | |
:(($(esc(x.args[1])),$(esc(x.args[2])))) | |
end | |
elseif ex.head == :typed_dict_comprehension | |
ex.head = :vcat | |
(sym, expr) = ex.args[2].args | |
range = ex.args[3].args[2] | |
args = Expr[] | |
@eval begin | |
for $(sym) in $(range) | |
push!($(args),:(($(esc($(sym))),$(esc($(expr)))))) | |
end | |
end | |
ex.args = args | |
else | |
error("Requires dictionary literal") | |
end | |
ex | |
end | |
A = [ 1 => "A", 2 => "B" ] | |
for (k,v) in @ordered A | |
println(k, " ", v) | |
end | |
f(x) = x^2 - x + 3 | |
for (k,v) in @ordered { i => f(i) for i in 1:2:6 } | |
println(k," ",v) | |
end | |
for (k,v) in @ordered [ 1 => "A", 2 => "B" ] | |
println(k," ",v) | |
end | |
println(@ordered [ 1=>2, 2=>3 ]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment