In julia, how to dispatch different kinds of "MutableNamedTuple"

52 Views Asked by At

My Julia code uses many different kinds of MutableNamedTuples e.g.

box = MutableNamedTuple

CSV(file::String)  = box(rows=[], file=file)
NUM() = box(n=0,mu=0, sd=0, m2=0)

I want to dispatch methods on the different kinds of MutableNamedTuples.

But how do I do that?

Is it possible to generate subtypes of MutableNamedTuples?

Or is there a different approach I should take?

(Ideally, one as succinct as using MutableNamedTuples but I'll take anything, with thanks.)

1

There are 1 best solutions below

3
Przemyslaw Szufel On

You can dispatch but it seems to be less comfortable than using mutable structs.

Consider the following functions:

using MutableNamedTuples

f(a::MutableNamedTuple{(:x, :y), Tuple{Base.RefValue{Int64}, Base.RefValue{Int64}}}) = 10*a.x

f(a::MutableNamedTuple{(:x, :z), Tuple{Base.RefValue{Int64}, Base.RefValue{Int64}}}) = 100*a.x

And now you could do

julia> a1 = MutableNamedTuple(x=1, y=2);

julia> a2 = MutableNamedTuple(x=1, z=2);

julia> f(a1)
10

julia> f(a2)
100

If you want to dispatch only on field names you could do:

julia> f(a::MutableNamedTuple{(:x, :z), T}) where T = 1000*a.x;

julia> f(MutableNamedTuple(x=1.0, z=2))
1000.0