Can functions share background state variables in Julia?

Viewed 48

In object-oriented languages, if I had a bunch of functions that all required the same set of parameters, I would create a helper class and have the functions be methods for that class.

In julia, I have an NCDataset and a set of functions that do something with the value in the dataset at a given variable, X, Y, Z, and 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

However this is kind of verbose. Is there a way to do this so that the functions share state variables that are initialized somehwere? Or is that not a paradigm in multiple-dispatch languages?

1 Answers

Structures allow property destructuring, so you can turn them into local variables in the function:

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

For very short functions like this, this at least makes things less cluttered and easier to read. For longer functions, this can be a lot less verbose.


You can also destructure directly on the argument line:

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)

If you have the helper be a NamedTuple or a Dictionary, you can also do:

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...)
Related