4

Is there any way to define a function accepting only tuples of fixed sizes, but different data types in them?

We can use something like this

f(x::NTuple{N}...) where {N} = ...

to enforce tuples of the same size (but with content of the same type), and something like this

f(x::Tuple...) = ...

to accept non-homogenous sequences (but variable in length).

Is there any way to achieve both simultaneously?

Šimon Mandlík
  • 303
  • 1
  • 6

1 Answers1

3

Tuples are covariant, see https://docs.julialang.org/en/latest/manual/types/#Tuple-Types-1, so you can use Any to allow any type. Therefore you can do it either this way:

f(x::Tuple{Any,Any}...)  = ...

which is probably OK for tuples having a small number of elements, or this way:

f(x::Tuple{Vararg{Any,10}}...) = ...

or

f(x::NTuple{10, Any}...) = ...

which is a general way allowing you to specify the number of elements of the tuple using a parameter (10 in this example).

If you do not know the size of the tuple but just want them to be the same size then you can write:

f(x::Tuple{Vararg{Any,N}}...) where N = ...

or

f(x::NTuple{N, Any}...) where N = ...
Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • 1
    Thank you! that solved my problem. `NTuple{N, T}` is a shorthand for `Tuple{Varargs{T, N}}`, so you can gain a little bit more readability by replacing it. – Šimon Mandlík Jul 26 '18 at 14:02
  • Sure, thanks - I have edited the answer. I had the `Vararg` version in my head because `NTuple` is rewritten as `Vararg` internally and I often needed the following form `Tuple{Vararg{Int}}` (so that you accept a tuple of `Int`s but do not have to specify the size of the tuple). The key thing is that `Vararg` and `NTuple` have reversed order of parameters so you can leave out different parameter. – Bogumił Kamiński Jul 26 '18 at 14:30