Last active
April 23, 2017 17:30
-
-
Save Ismael-VC/42ec58216dbb8aeab1413c07a49b1b35 to your computer and use it in GitHub Desktop.
Julia macro for Python like dict literals.
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 DictMacro | |
export @dict | |
""" | |
@dict {k₁: v₁, k₂: v₂, …, kₙ₋₁: vₙ₋₁, kₙ: vₙ} | |
Use Python's `dict`, JSON like syntax for `Dict` literals. | |
# Usage | |
``` | |
julia> @dict {"a": :b, 'c': 1, :d: π, Function: print, (1:10): range(1, 10)} | |
Dict{Any,Any} with 5 entries: | |
1:10 => 1:10 | |
Function => print | |
"a" => :b | |
:d => π = 3.1415926535897... | |
'c' => 1 | |
``` | |
""" | |
macro dict(expr) | |
if expr.head ≠ :cell1d || any(sub_expr.head ≠ :(:) for sub_expr ∈ expr.args) | |
error("syntax: expected `{k₁: v₁, k₂: v₂, …, kₙ₋₁: vₙ₋₁, kₙ: vₙ}`") | |
end | |
block = Expr(:call, :Dict) | |
for pair in expr.args | |
k, v = pair.args | |
push!(block.args, :($k => $v)) | |
end | |
return esc(block) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment