Alec
Alec

Reputation: 4472

How to promote named tuple fields to variable and associated value?

I have a model with many parameters where I am passing them as a named tuple. Is there a way to promote the values into the variable scope in my function?

parameters = (
    τ₁ = 0.035,   
    β₁ = 0.00509, 
    θ = 1,
    τ₂ = 0.01,    
    β₂ = 0.02685,
    ... 
)

And then used like so currently:

function model(init,params) # params would be the parameters above
    foo = params.β₁ ^ params.θ 
end

Is there a way (marco?) to get the parameters into my variable scope directly so that I can do this:

function model(init,params) # params would be the parameters above
    @promote params # hypothetical macro to bring each named tuple field into scope
    foo = β₁ ^ θ 
end

The latter looks a lot nicer with some math-heavy code.

Upvotes: 3

Views: 365

Answers (1)

fredrikekre
fredrikekre

Reputation: 10984

You can use @unpack from the UnPack.jl package1:

julia> nt = (a = 1, b = 2, c = 3);

julia> @unpack a, c = nt; # selectively unpack a and c

julia> a
1

julia> c
3

1 This was formerly part of the Parameters.jl package, which still exports @unpack and has other similar functionality you might find useful.


Edit: As noted in the comments, writing a general macro @unpack x is not possible since the fieldnames are runtime information. You could however define a macro specific to your own type/namedtuple that unpacks

julia> macro myunpack(x)
           return esc(quote
               a = $(x).a
               b = $(x).b
               c = $(x).c
               nothing
           end)
       end;

julia> nt = (a = 1, b = 2, c = 3);

julia> @myunpack nt

julia> a, b, c
(1, 2, 3)

However, I think it is more clear to use the @unpack since this version "hides" assignments and it is not clear where the variables a, b and c comes from when reading the code.

Upvotes: 5

Related Questions