Struct containing a tuple of unknown length

I’m thinking about some kind of immutable version of the following mutable object:

mutable struct MGlob
id::Int
children::Array{MGlob}
end

For example the immutable version, called struct Glob, would have the same id field but the children could be a Tuple of Globs now. If I use that approach, I guess I have two problems:

  1. how to declare Glob, and
  2. how to write the most efficient function to convert any MGlob to a Glob.
    The conversion would change each MGlob object in the array of MGlobs to a Glob object in the tuple of Globs. For some reason I can’t get it. Thanks for any help!

Is this what you’re looking for?

struct Glob{N}
    id::Int
    children::NTuple{N,Glob}
end

Glob(mg::MGlob) = Glob{length(mg.children)}(mg.id, ntuple(i -> Glob(mg.children[i]), length(mg.children)))
2 Likes

Yes, that seems to work very well! I’ll have to think more about the parameter N but it does the job. I appreciate the help.

You will have to be very careful with type stability if you expect to actually see a performance improvement from the immutable version.

Unless the number of children is constant enough to achieve that, so you can actually write

struct Glob{N,G<:Glob}
    id::Int
    children::NTuple{N,G}
end

I would stick with the MGlobs.

2 Likes

That is good to know too. Right now I am interested in immutability for another reason also. Once I have constructed a big tree I would like to make sure I can’t inadvertently modify some part of it. (Well, maybe there are different ways to achieve the same goal which would be better!)
Thanks!