Macro to convert list of variables to Dict keyed by variable name

For debugging purposes, I’d like to be able to write something like:

d = @makedict( a, b, c )

which would expand to

d = Dict( :a=>a, :b=>b, :c=>c )

I just can’t seem to work out how to do this…

1 Like

See @pack in Parameters.jl

d = Dict{Symbol,Any}(:a=>5.0,:b=>2,:c=>"Hi!")
@unpack a, c = d
a == 5.0 #true
c == "Hi!" #true

d = Dict{Symbol,Any}()
@pack d = a, c
d # Dict{Symbol,Any}(:a=>5.0,:c=>"Hi!")
julia> a = 1; b = 2; c = 3;

julia> macro makedict(vars...)
           expr = Expr(:call, :Dict)
           for i in 1:length(vars)
               push!(expr.args, :($(QuoteNode(vars[i])) => $(esc(vars[i]))))
           end
           return expr
       end
@makedict (macro with 1 method)

julia> d = @makedict(a, b, c)
Dict{Symbol,Int64} with 3 entries:
  :a => 1
  :b => 2
  :c => 3
1 Like

esc

QuoteNode(vars[i])

1 Like

Merci!