函数可以在Julia中共享后台状态变量吗



在面向对象语言中,如果我有一堆函数都需要相同的参数集,我会创建一个助手类,并将这些函数作为该类的方法。

在julia中,我有一个NCDataset和一组函数,它们对数据集中给定变量X、Y、Z和T的值做一些事情。

struct Helper
var::String
x::Int64
y::Int64
z::Int64
t::Int64
end
function do_thing_1(helper::Helper, ds::NCDataset)
return ds[helper.var][[helper.x,helper.y,helper.z,helper.t]*2
end
function do_thing_2(helper::Helper, ds::NCDataset)
return ds[helper.var][[helper.x,helper.y,helper.z,helper.t]/2.0
end

然而,这有点冗长。有没有一种方法可以做到这一点,使函数共享在其他地方初始化的状态变量?或者这不是多种调度语言的范例吗?

结构允许属性析构函数,因此您可以将它们转换为函数中的局部变量:

function do_thing_1(helper::Helper, ds::NCDataset)
(; var, x, y, z, t) = helper
return ds[var][x, y, z, t]*2
end

对于像这样很短的函数,这至少可以减少混乱,更容易阅读。对于较长的函数,这可以减少很多冗长的内容。


您也可以直接在参数行上进行析构函数:

function do_thing_1((; var, x, y, z, t), ds::NCDataset)
return ds[var][x, y, z, t]*2
end
do_thing_1(helper, ds)

如果helperNamedTupleDictionary,您也可以执行:

function do_thing_1(ds::NCDataset; var, x, y, z, t)
return ds[var][x, y, z, t]*2
end
do_thing_1(ds; helper...)

最新更新