ComponentArrays.jl icon indicating copy to clipboard operation
ComponentArrays.jl copied to clipboard

Construct ComponentArray from containers for keys and values

Open itsdfish opened this issue 3 years ago • 2 comments

Hi,

My apologies if the following functionality already exists. In some cases, it might be convenient to construct a ComponentArray with a collection of keys and a collection of values. With this approach, you do not have to hard code the values into the constructor. NamedTuples provides this functionality:

using ComponentArrays

k = (:a,:b)
v = [1,2]
NamedTuple{k}(v)
(a = 1, b = 2)

Perhaps one annoyance is that the keys must be in a tuple. Using similar syntax, the returned object is a Vector{Int}

ComponentArray{k}(v) An alternative syntax could be:

ComponentArray(k, v)

itsdfish avatar Jan 21 '22 21:01 itsdfish

That does seem useful. Right now the constructors for ComponentArrays are horribly overloaded, though. For example, you noticed that it returned a Vector{Int}; I don't like this at all--constructors should never do that--but it's necessary for the way things are set up at the moment. It's been a longstanding issue to fix all of this, but I just haven't had a really good reason to spend that time yet (and it will take quite a bit of time, I think). Unfortunately, it makes me a little hesitant to add more to the constructors right now, especially given that ComponentArray{k}(v) already means something (if k was an Axis, it would make a valid ComponentArray). Here's a stop-gap that might work for you for the time being, though (and might be worth actually adding, but I'll have to think about that):

julia> make_axis(symbols) = Axis(NamedTuple(symbols .=> eachindex(symbols)))
make_axis (generic function with 1 method)

julia> ComponentArray(v, make_axis(k))
ComponentVector{Int64}(a = 1, b = 2)

jonniedie avatar Jan 21 '22 22:01 jonniedie

I completely understand your reluctance to add this to the package. I appreciate the stopgap solution.

itsdfish avatar Jan 21 '22 23:01 itsdfish