Reputation: 1529
I want to make a struct that works something like struct C
below, but where C.a
and C.b
are of the same type:
struct C
a::Array
b::Array
function C(a, b)
length(a) == length(b) || throw(DimensionMismatch())
new(a, b)
end
end
I thought this would be trivial to implement by doing the following:
struct D{T<:Int}
a::Array{T}
b::Array{T}
function D(a, b)
length(a) == length(b) || throw(DimensionMismatch())
new(a, b)
end
end
But it throws an error:
# syntax: too few type parameters specified in "new{...}" around
I found the beginning of a solution for this on the julia discourse.
struct E{T<:Int}
a::Array{T}
b::Array{T}
function E(a::Array{S}, b::Array{S}) where S<:Int
length(a) == length(b) || throw(DimensionMismatch())
new{S}(a, b)
end
end
The error is gone. But for some reason it doesn't work with all Int
v = Array{Int64}([1,2])
w = Array{Int32}([1,2])
E(v, v)
# E{Int64}(Int64[1, 2], Int64[1, 2])
E(v, v)
# MethodError: no method matching Main.workspace321.E(::Array{Int32,1}, ::Array{Int32,1})
Does somebody have an idea what going on here?
Upvotes: 3
Views: 913
Reputation: 1529
I found the problem Int
is an alias (I think, I couldn't find it in the docs.) for Int64
. In any case:
julia> Int32 <: Integer
true
julia> Int32 <: Int
false
julia> Int64 <: Int
true
julia> Int64 == Int
true
help?> Int
search: Int Int8 Int64 Int32 Int16 Int128 Integer ...
Int64 <: Signed
64-bit signed integer type.
So this works:
struct E{T<:Integer}
a::Array{T}
b::Array{T}
function E(a::Array{S}, b::Array{S}) where S<: Integer
length(a) == length(b) || throw(DimensionMismatch())
new{S}(a, b)
end
end
Upvotes: 5