How to write the type signature of a tuple of types?


For example, I have a type

abstract type Axis{a,A} end

How can I express in function type signature that I have a tuple of unknown numbers of Axis with different type parameters? For instance,

julia> Tuple{Axis{a,A}, Axis{b,B}} where {a,b,A,B}
Tuple{Axis{a,A},Axis{b,B}} where B where A where b where a

julia> Tuple{Axis{a,A}, Axis{b,B}, Axis{c,C}} where {a,b,A,B,c,C}
Tuple{Axis{a,A},Axis{b,B},Axis{c,C}} where C where c where B where A where b where a

How can I express them in a general unified type? I tried as follows but failed.

julia> Tuple{Axis...}
ERROR: MethodError: no method matching iterate(::Type{Axis})
Closest candidates are:
  iterate(::Core.SimpleVector) at essentials.jl:589
  iterate(::Core.SimpleVector, ::Any) at essentials.jl:589
  iterate(::ExponentialBackOff) at error.jl:171
 [1] append_any(::Tuple{DataType}, ::Vararg{Any,N} where N) at ./essentials.jl:426
 [2] top-level scope at none:0

In Python I can have

from typing import Tuple
# To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. 
Tuple[int, ...]

which is very handy. I want something similar in Julia.


Try the special Vararg type:

julia> ("a",) isa Tuple{String, Vararg{Int}}

julia> ("a",1,1,1) isa Tuple{String, Vararg{Int}}
1 Like

I think you are looking for NTuple{Axis,2} etc. Also look at Vararg. Search the manual and you will find examples.

1 Like

Thanks, just to point out that

NTuple{N, T}

  A compact way of representing the type for a tuple of length N where all elements are
  of type T.

I found that I could write NTuple{N, T} where N to solve this. I did not think about using NTuple was because I thought first I need to specify N, which is not known. And also, a UnionAll type does allow me to have different parameterized Axiss:

julia> struct B{a, A} <: Axis{a, A}

julia> B{a}(data::A) where {a, A} = B{a, A}(data)

julia> (B{:s}(rand(3)), B{:q}([1,2,4,5])) isa NTuple{N, Axis} where N