3

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?

1
  • 1
    If arguments is a variable length tuple of positional parameters then they don't have names. If on the other hand, the definition is function test(;arguments...) which makes arguments named parameters, then Dict(a[1]=>a[2] for a in arguments) should usually work (except for edge cases with argument names repeating etc). Commented Sep 13, 2017 at 22:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.