Julia 将数据类型的向量约束为特定抽象类型
是否可以创建一个函数,该函数接受一个Julia 将数据类型的向量约束为特定抽象类型,julia,Julia,是否可以创建一个函数,该函数接受一个::Vector{DataType},但将所有成员约束为从特定抽象类型继承的类型 例如: # this code works but does not constrain the type function foo{D<:DataType}(arr::Vector{D}) ... end # this is kind of the syntax I'd like, but Type{Int} !<: Type{Integer} funct
::Vector{DataType}
,但将所有成员约束为从特定抽象类型继承的类型
例如:
# this code works but does not constrain the type
function foo{D<:DataType}(arr::Vector{D})
...
end
# this is kind of the syntax I'd like, but Type{Int} !<: Type{Integer}
function bar{D<:Type{Integer}}(arr::Vector{D})
...
end
#此代码有效,但不约束类型
函数fo{d我不确定这是可能的(干净的)编译时间检查。你可以考虑使用<代码> Value/Copy>类型,但是这将是混乱的,而且可能会更慢。我只想让它运行时检查:
julia> function bar{T}(::Type{T}, arr::Vector{DataType})
if all(x->x<:T, arr)
println("ok")
else
println("bad")
end
end
bar (generic function with 1 method)
julia> bar(Integer, [Int,Int32])
ok
julia> bar(Integer, [Int,Int32,Float64])
bad
julia>函数条{T}(::类型{T},arr::向量{DataType})
如果全部(x->x条(整数,[Int,Int32])
好啊
julia>bar(整数,[Int,Int32,Float64])
坏的
您的使用案例是什么?可能有一个更干净的替代方案。只是为了澄清为什么功能条{T类型
是参数化类型,所以它的类型参数是不变的。为什么不使用功能条{T@GnimucKey:谢谢你的建议。我在创建与该表单匹配的数组时遇到问题:bar{ Thmm,我发现我只是从一个坑跳到另一个坑。那个定义行不通!我会发布一个解释的解释,因为没有足够的注释空间。谢谢!我的用例适合一系列数据集模型。需要一个数据类型。我想循环查看我的分发类型,并为每个分发类型安装一个模型。我将接受此帖子,因为没有解决方案。如果有人找到了,请告诉我们!您看到上面Gnumic Key的答案(发布在评论中)了吗?@如果此方法不起作用,请查看我下面的解释。
function bar{D<:Type{Integer}}(arr::Vector{D})
...
end
function bar{T<:Integer}(arr::Vector{Type{T}})
...
end
julia> bar([Int64, Int32])
ERROR: MethodError: `bar` has no method matching bar(::Array{DataType,1})
julia> methods(bar)
bar{T<:Integer}(arr::Array{Type{T<:Integer},1})
julia> [Int64, Int32]
2-element Array{DataType,1}:
Int64
Int32
# we know that DataType is a subtype of Type{T},
# where T is a `TypeVar` \in [Bottom, Any].
julia> subtypes(Type)
3-element Array{Any,1}:
DataType
TypeConstructor
Union
julia> S = TypeVar(:S, Union{}, Integer, true)
S<:Integer
# but Type{S} is not a subtype of DataType
julia> Type{S} <: DataType
false
julia> Type{S} <: Type
true
julia> a = Array(Type{S}, 2)
2-element Array{Type{S<:Integer},1}:
#undef
#undef
julia> a[1] = Type{Int32} # or Int32
Type{Int32}
julia> a[2] = Type{Float32} # or Float32
Type{Float32}
julia> a
2-element Array{Type{S<:Integer},1}:
Type{Int32}
Type{Float32}