Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 616
krcools Avatar asked Dec 03 '15 18:12

krcools


1 Answers

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
like image 195
mbauman Avatar answered Oct 15 '22 06:10

mbauman