NTuple length dependent on parameter of type

tuple
parametric-types

#1

Is it possible to have a type say:

struct A{B}
field::NTuple{N, Int}
end

Say B is always a number so A{5}, A{7} and so on.
Is it possible to specify in the type definition that N depends on B, in some manner e.g:

struct A{B}
field::NTuple{(B / 64), UInt64}
end

The above doesn’t work, but hopefully shows what I’d like to enforce.


#2

No, that is not possible. See Algebraic constraints for type parameters.


#3

As @mauro3 pointed out, that is not possible.
But you are able to enforce that by defining a inner constructor:

julia> struct A{B,N}
       field::NTuple{N,Int}
       function A{B}(x) where {B}
         N = B÷64
         N == length(x) || throw(ArgumentError("Tuple of incorrect length"))
         return new{B,N}(x)
       end
       end

julia> x = (1,2)
(1, 2)

julia> y = A{128}(x)
A{128,2}((1, 2))

julia> z = A{64}(x)
ERROR: ArgumentError: Tuple of incorrect length
Stacktrace:
 [1] A{64,N} where N(::Tuple{Int64,Int64}) at ./REPL[2]:5

julia> z = A{64}((1,))
A{64,1}((1,))