Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a name macro for variables from a functions inputs

Tags:

macros

julia

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?

like image 612
atomsmasher Avatar asked Apr 05 '26 19:04

atomsmasher


1 Answers

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

like image 66
Chris Rackauckas Avatar answered Apr 08 '26 08:04

Chris Rackauckas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!