Compile-time arithmetic for parameterized types

I want to define type like this:

struct A{L}
  x::NTuple{L,Int}; y::NTuple{L^2,Int}
end

Here L is known at compile-time. Therefore L^2 could also be known at compile-time in principle. But the example above is a syntax error. I was forced to do this:

struct A{L,L2}
  x::NTuple{L,Int}; y::NTuple{L2,Int}
  function A{L,L2}(x::NTuple{L,Int}, y::NTuple{L2,Int}) where {L,L2}
     @assert L2 == L^2
     new{L,L2}(x,y)
  end
end

But this ends up computing the square of L at runtime (when I check for L2 == L^2). I would like to avoid this runtime calculation, since L is known at compile-time. Moreover, I don’t want to let L,L2 be independent values in A{L,L2}, because having a A{L,L2} with L2!=L^2 would be an invalid state. Therefore the check is necessary, but ideally it should be a compile-time check.

Is there a better way to do this kind of thing?

1 Like

No. See https://github.com/JuliaLang/julia/issues/18466 and https://github.com/vtjnash/ComputedFieldTypes.jl

2 Likes