Functions taking NTuple as arguments but imposing (static) size constraints, how to define them?

Viewed 80

I want to define functions taking NTuples as arguments but with with size constraints.

The idea would be to declare something like:

foo(x::NTuple{K-1,Int},y::NTuple{K,Int}) where {K} = "ok"

However this is not a correct Julia code.

My question is: how to define such kind of functions in Julia?


(For illustration purpose only): for C++ coders, my question is equivalent to "how to translate this kind of C++ code

template <size_t N>
foo(const std::array<int, N-1>& x, const std::array<int, N>& y) 
{ ... }

into well formed Julia code."

1 Answers

In this specific case you can do:

foo(x::NTuple{M,Int},y::Tuple{Int, Vararg{Int,M}}) where {M} = "ok"

as the difference in dimensions is fixed.

In a more general case the only thing I know of is to add a condition inside the function:

foo(x::NTuple{M,Int},y::NTuple{K,Int}) where {M,K} = 
    M + 1 == K ? "ok" : throw(ArgumentError("dimension mismatch"))

and the conditional check should be optimized out by the compiler (at least in this case it seems to be optimized under Julia 1.0.3).

Related