Function signature with tuple argument of a given length


#1

Hi,

I want to express that a function accepts as first argument a tuple of length consistent with the type parameter of the second argument. This

function foo(x::NTuple{M}, b::SomeOtherType{M}) where {M} end

is not what I want, because it restricts the type of the entries of x to be the same.

Any ideas?

Thanks,

Davide


#2

You can use a Tuple{Vararg{Any, N}}:

julia> f(x::Tuple{Vararg{Any, N}}, y::Tuple{Vararg{Any, N}}) where {N} = println(N)
f (generic function with 1 method)

julia> f((1,2.0), ("hello", π))
2

#3

Thanks.

This could be a good edit to the docs.


#4

I believe what you are looking for is this.

function foo(x::NTuple{N,M}, b::SomeOtherType{M}) where {N,M} end

NTuple{M} is and alias for a NTuple of length N, but not type.


#5

Just use f(x::NTuple{M,Any}, b::SomeOtherType{M}) where {M}, now the entries of x can be of Any type.

(which is equivalent to the solution of @rdeits since NTuple{M,Any} = Tuple{Vararg{Any,M}}).


#6

This will only match tuples where the elements have the same type.