我有一个包含许多参数的模型,我将它们作为命名元组传递。有没有办法将值提升到我的函数中的变量范围?
\nparameters = (\n \xcf\x84\xe2\x82\x81 = 0.035, \n \xce\xb2\xe2\x82\x81 = 0.00509, \n \xce\xb8 = 1,\n \xcf\x84\xe2\x82\x82 = 0.01, \n \xce\xb2\xe2\x82\x82 = 0.02685,\n ... \n)\nRun Code Online (Sandbox Code Playgroud)\n然后像现在这样使用:
\nfunction model(init,params) # params would be the parameters above\n foo = params.\xce\xb2\xe2\x82\x81 ^ params.\xce\xb8 \nend\nRun Code Online (Sandbox Code Playgroud)\n有没有办法(marco?)直接将参数放入我的变量范围,以便我可以执行此操作:
\nfunction model(init,params) # params would be the parameters above\n @promote params # hypothetical macro to bring each named tuple field into scope\n foo = \xce\xb2\xe2\x82\x81 ^ \xce\xb8 \nend\nRun Code Online (Sandbox Code Playgroud)\n后者通过一些数学密集型代码看起来要好得多。
\n您可以使用包1@unpack中的:UnPack.jl
julia> nt = (a = 1, b = 2, c = 3);
julia> @unpack a, c = nt; # selectively unpack a and c
julia> a
1
julia> c
3
Run Code Online (Sandbox Code Playgroud)
1这是以前的包的一部分Parameters.jl,它仍然导出@unpack并具有您可能会发现有用的其他类似功能。
编辑:如评论中所述,编写通用宏@unpack x是不可能的,因为字段名称是运行时信息。但是,您可以定义一个特定于您自己的类型/命名元组的宏来解包
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)
Run Code Online (Sandbox Code Playgroud)
然而,我认为使用 更清晰,因为这个版本“隐藏”了赋值,并且在阅读代码时@unpack不清楚变量a,b和来自哪里。c