问题: Julia是否有严格的子类型运算符?
注意:操作员<:是不是一个严格的亚型运营商,因为Number <: Number计算结果为true.我感兴趣的运营商,将评估为false为Number <: Number,但true对Int <: Number.
可能的用例:考虑定义的函数:
MyFunc{T<:Union(Int, String)}(x::Array{T, 1}, y::Array{T, 1)})
Run Code Online (Sandbox Code Playgroud)
目前,函数约束着x并y为相同的类型,其中该类型是阵列Int,String或Union(Int, String).但是使用严格的子类型运算符,我可以强制输入数组为类型Int或String,并消除(相当奇怪的)Union(Int, String)场景.
我认为 Julia 中没有这样的运算符,但编写一个执行相同检查的函数可能会很容易:
strictSubType{T,U}(::Type{T}, ::Type{U}) = T <: U && T != U # note: untested!
Run Code Online (Sandbox Code Playgroud)
但是,我不得不质疑你的用例。如果你真正想要的是类似的东西
function my_func{T<:String}(x::Vector{T}, y::Vector{T})
# handle strings
# note that String is an abstract type, inherited by e.g. ASCIIString and UTF8String
end
function my_func(x::Vector{Int}, y::Vector{Int})
# handle ints
# note that Int is a concrete type (actually an alias for either Int32 or Int64,
# depending on your platform) so no generic type parameter is necessary
end
Run Code Online (Sandbox Code Playgroud)
然后写它。如果您有可以共享的逻辑部分,请将其重构为单独的方法,您可以在其中放宽类型参数(或完全省略它们)。
更新,回应您的评论:
如果这两个方法应该做完全相同的事情,那么您最好使用鸭子类型,并且根本不指定函数参数的类型:
funciton my_func(x, y)
# handle ints, strings and anything else that supports things you need (e.g. > and <)
end
Run Code Online (Sandbox Code Playgroud)
Julia 将为您调用的每种类型组合编译特定的方法,因此您仍然可以获得同样快速的代码;如果函数类型稳定,那么对于任何组合来说它都会很快(有关其工作原理的更全面解释,请参阅 Julia 文档)。如果您想确保两个参数是向量,并且它们属于同一类型,我建议进行对角分派(也在文档中进行了更彻底的解释):
function my_func{T}(x::AbstractVector{T}, y::AbstractVector{T})
# handle stuff
end
Run Code Online (Sandbox Code Playgroud)
请注意,我使用AbstractVector而不是Vector- 这允许使用一些其他容器类型,其行为也类似于具有类型元素的向量T,从而最大限度地提高函数对其他编码人员的可用性。