I am trying to define a parametric type MyType{T1,T2,T3,...} where the number of Ti’s may vary according to constructor’s arg… I’ve done something similar to:
struct MyType{T}
m::Union{T,Tuple{Vararg{T}}} where T
MyType(a::A...) where A = new{typeof(a)}(a)
end
…but it doesn’t really do what I need. Any suggestion?
But one parameter can subtype Tuple, thus be any length. You won’t get extra parameter names to annotate fields with, but it doesn’t seem like you need it anyway. This will have a different concrete type for a different tuple length:
julia> struct MyType{T, S<:Tuple{T,T,Vararg{T}}} # tuple >= 2
m::Union{T, S}
MyType(a::A...) where A = new{A, typeof(a)}(a)
end
julia> MyType(1,2,3,4)
MyType{Int64, NTuple{4, Int64}}((1, 2, 3, 4))
julia> MyType(1,2)
MyType{Int64, Tuple{Int64, Int64}}((1, 2))
julia> MyType(1)
ERROR: TypeError: in MyType, in S, expected S<:Tuple{Int64, Int64, Vararg{Int64}}, got Type{Tuple{Int64}}
Not sure how you intend the 1-argument scenario to infer the alternate tuple length though. Might be easier to go for a 1-tuple instead, just store tuples in m.
The usage of MyType will be 90% with a single object in field m and I already have a lot of code implemented with MyType having m as a single object, I don’t want to go and change hundreds of lines… I’m just adding the ability to have multiple models stored in m… having MyType{A,B,C,...} would’ve been cool though!
Would an alternative thought maybe be to have the storage “the other way around”, so a Vector[MyType] (or tuple) instead of a tuple “inside”?
That would be basically broadcasting in the functions then (or dispatch on the vector my type case, depending on what your functions do.
Of oourse that depends a lot on the actual situation, but maybe keeping the MyType a “simpler structure” might be something that could be nice.
Yeah, but implemented it this way because some models (financial) come with the “parameters”, the very model creates its specific framework, its specific world… It was to enforce those ideas…
But yeah, the struct is simple, lightweight… I wanted it to dispatch… it does so with MyType{Tuple{A,B,C}}…