Reputation: 745
If I have 2 variables, a=[.3, .2, .4]; b=[.1, .2, .3];
I can create a string with the name of the variable using a macro:
macro varname(arg)
string(arg)
end
@varname(a)
now say I have a function and I want to pass it an arbitrary number of arguments and use the actual variable names that are being given to function to create dictionary keys:
function test(arguments...)
Dict(Symbol(@varname(i)) => i for i in arguments)
end
this won't work because @varname
will take i
and create "i"
, so for example:
out=test(a,b)
the output I would like is:
Dict("a" => [.3, .2, .4], "b" => [.1, .2, .3])
Is there a way to achieve this behavior?
Upvotes: 3
Views: 278
Reputation: 19132
Parameters.jl has such a macro. It works like this:
using Parameters
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!")
If you want to know how it's done, just check its source:
https://github.com/mauro3/Parameters.jl/blob/v0.7.3/src/Parameters.jl#L594
Upvotes: 2