9

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?

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.