Expressions depending on integer type parameters in type definitions in Julia are not allowed

I want to define the type around FixedSizeArrays.Vec {N, T}, where N is the function of the type parameter:

using FixedSizeArrays type MT{N} x::Vec{N,Int} y::Vec{N+1,Int} end 

As a result, an error message appears:

 ERROR: MethodError: `+` has no method matching +(::TypeVar, ::Int64) Closest candidates are: +(::Any, ::Any, ::Any, ::Any...) +(::Int64, ::Int64) +(::Complex{Bool}, ::Real) ... 

Apparently, simple arithmetic with integer type parameters is not allowed, even if the result may be known at compile time. Does anyone know of a workaround for this limitation?

+5
source share
1 answer

Apparently, simple arithmetic for parameters with integer type is not allowed

Yes, this is a limitation with type parameters. The standard method is a parameter of the second type. Then you can apply the invariants of the parameters to the internal constructor:

 type MT{N,Np1} x::Vec{N,Int} y::Vec{Np1,Int} function MT(x,y) N+1==Np1 || throw(ArgumentError("mismatched lengths; y must be one element longer than x")) new(x,y) end end # Since we define an inner constructor, we must also provide the # outer constructor to allow calling MT without parameters MT{N,M}(x::Vec{N,Int}, y::Vec{M,Int}) = MT{N,M}(x,y) 

Example:

 julia> MT(Vec(1,2,3),Vec(1,2,3,4)) MT{3,4}(FixedSizeArrays.Vec{3,Int64}((1,2,3)),FixedSizeArrays.Vec{4,Int64}((1,2,3,4))) julia> MT(Vec(1,2,3),Vec(1,2,3)) ERROR: ArgumentError: mismatched lengths; y must be one element longer than x 
+6
source

Source: https://habr.com/ru/post/1237357/


All Articles