julia - 如何将命名元组字段提升为变量和关联值?
问题描述
我有一个带有许多参数的模型,我将它们作为命名元组传递。有没有办法将值提升到我的函数中的变量范围?
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
后者看起来好多了一些数学繁重的代码。
解决方案
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.
推荐阅读
- php - MySQL:按照一定的字母顺序对查询进行排序
- javascript - JavaScript 函数中的参数
- c - 当输入以单行形式给出时,如何从 scanf 获取二维数组中的输入?
- c# - Unity 游戏在 iOS 上崩溃,但在 Android 上没有
- python-3.x - 在客户端 PC 上写入文件并运行它
- android - 有没有办法单击按钮/图像按钮并创建一个下拉文本视图,将其他按钮推离屏幕?
- excel - Cannot apply a VBA Autofilter to a table which I export to a CSV
- influxdb - 如何在电报中设置测量、字段/标签键和值?
- python - 如何在 for 循环和 if 语句中简化 for 循环?
- python - 为什么这个简单的递归树遍历算法会失败?