I want to define a type around a FixedSizeArrays.Vec{N,T} where N is a function of the type parameter:
using FixedSizeArrays
type MT{N}
x::Vec{N,Int}
y::Vec{N+1,Int}
end
This results in the error message:
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 can be known at compile time. Does anyone know of a workaround for this limitation?
Apparently, simple arithmetic for with integer type parameters is not allowed
Yes, this is a limitation with type parameters. The standard way around this is with a second type parameter. You can then enforce the parameter invariants with an inner 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With