How to dispatch on a Tuple with unknown length, but elements have same abstract type?

Consider this example:

a = (complex(1,2), complex(1.0, 2.0))

The length of a is not fixed to 2, but could be arbitrary.
Is there a way to dispatch on this?
I tried

a isa NTuple{N, <: Complex} where N

but this is obviously false, because a isn’t a NTuple.
It works with

a = (complex(1.0,2.0), complex(1.0, 2.0))


julia> a = (complex(1,2), complex(3.0,4.0))
(1 + 2im, 3.0 + 4.0im)

julia> a |> typeof
Tuple{Complex{Int64}, ComplexF64}

julia> a isa NTuple{N, <: Complex} where N


julia> complex(1,2) |> typeof

julia> complex(3.0,4.0) |> typeof
ComplexF64 (alias for Complex{Float64})

Sorry, overlooked the abstract type in the question.

Might wanna use

julia> a isa NTuple{N,Complex{<:Real}} where N
1 Like

I figured out that I have to leave out the first <: in the second argument of the NTuple.
This works, too:

a isa NTuple{N, Complex} where N

The rules for Tuple subtyping are special: tuples are covariant wrt their type parameters.
That means, a is an NTuple{2, Complex}. On the other hand, a isa NTuple{2,T} where {T<:Complex} is false because of the diagonal rule.

1 Like