Dear all,
I have some trouble to infer the types of Tuples and NamedTuples. Let’s start with a simple tuple. If each field in the tuple is of the same type, I can state the type of the tuple as follows (MWE):
a = (:b, :c, :d)
typeof(a) #Tuple{Symbol, Symbol, Symbol}
typeof(a) <: NTuple{k, Symbol} where k #true
- Question
Let’s say now that I define a custom struct and I want that the tuple can only hold the custom structs, but the struct itself has parametric types. How can I force the tuple to only hold such custom structs? MWE:
struct Test1{A, B}
a :: A
b :: B
end
b = (Test1("1", :b), Test1(3., 4), )
typeof(b) #Tuple{Test1{String, Symbol}, Test1{Float64, Int64}}
typeof(b) <: NTuple{k, T} where {k, T<:Test1} #false
This would be useful to me if I want to have a field of another struct to only hold tuples of Test1 types. I can already do something more general, but
any tuple could be inserted, which is not what I want.
struct BigStruct{A<:Tuple}
a :: A
end
BigStruct(b) #working
I would like to force that field a
can only hold Tuples of Test1 types:
struct SafeBigStruct{k, T<:Test1}
a :: NTuple{k, T}
end
SafeBigStruct(b) # NOT working -> no method matching SafeBigStruct...
- Question
Extending this to NamedTuples, how would this work? As far as i understand, NamedTuple types contain the types of its keys and values:
c = (d = Test1("1", :d), e = Test1(3., 4), )
typeof(c) #NamedTuple{(:d, :e), Tuple{Test1{String, Symbol}, Test1{Float64, Int64}}}
The key values should always have type NTuple{k, Symbol} where k
, but just as in the previous question, I cannot infer the value types. Is there any way to get the NamedTuple type, such that it still enforces that all values have to be of type Test1
?