首页 > 解决方案 > 如何将命名元组字段提升为变量和关联值?

问题描述

我有一个带有许多参数的模型,我将它们作为命名元组传递。有没有办法将值提升到我的函数中的变量范围?

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

然后像现在这样使用:

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

有没有办法(marco?)直接将参数放入我的变量范围,以便我可以这样做:

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

后者看起来好多了一些数学繁重的代码。

标签: julia

解决方案


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.


推荐阅读