julia 0.6中不同类型字典的向量 [英] Vector of dictionaries of different types in julia 0.6
问题描述
我对 julia 0.6 中新的 where
语法有点困惑.我有这样的事情:
I am a bit confused about the new where
syntax in julia 0.6.
I have something like this:
a=Dict(["a"=>"b"])
b=Dict(["a"=>3])
c=Dict(["a"=>"c"])
我想要一个无需进行显式转换即可接收字典向量的函数.我试过了:
I want a function that receive a vector of dictionaries without having to make an explicit conversion. I tried with:
function bbb(a::Vector{Dict{String, Any}})
println(a)
end
它没有用.
然后我尝试了
function bbb(a::Vector{Dict{String, T} where T})
println(a)
end
bbb([a,b]) #Works
bbb([a,c]) #Fails
bbb([a,b,c]) #Works
为了进行显式转换,我已经用我能收到的每个组合重载了 bbb.但我仍然想知道如何正确地做到这一点.
I have overloaded bbb with every combination that I can recieve in order to make an explicit conversion. But I'm still wondering how is the proper way to do it.
推荐答案
这是在行动中的不变性.这是一个复杂的案例,因为有两个级别的参数化,但原理是一样的.
This is invariance in action. It's a complicated case since there are two levels of parameterization, but the principle is the same.
Dict{String, Any}
描述了一个字典,其中键是字符串,值类型正好是Any
.参数不变性意味着Dict{String, Int}
不是Dict{String, Any}
的子类型.Dict{String, T} where T
描述了所有带有字符串键的字典.类型 varT
可以匹配任何类型,包括Any
或Int
.
Dict{String, Any}
describes a dictionary where the keys are strings and the value type is exactlyAny
. Parametric invariance means thatDict{String, Int}
is not a subtype ofDict{String, Any}
.Dict{String, T} where T
describes all dictionaries with string keys. The type varT
can match any type, includingAny
orInt
.
现在,当您开始谈论字典向量时,同样的原则也适用:
Now, when you start talking about a vector of dictionaries, the same principle applies:
Vector{Dict{String, T} where T}
描述了一个向量,其中元素类型是exactlyDict{String, T} where T代码>.参数不变性意味着
Vector{Dict{String, Int}}
是 not 的子类型Vector{Dict{String, T} where T}
.Vector{D} where D <: (Dict{String, T} where T)
描述所有向量,其中元素是带有字符串键的字典.类型 varD
可以匹配任何键为字符串的字典类型,包括Dict{String, T} where T
或Dict{String, Int}代码>.
Vector{Dict{String, T} where T}
describes a vector where the element type is exactlyDict{String, T} where T
. Parametric invariance means thatVector{Dict{String, Int}}
is not a subtype ofVector{Dict{String, T} where T}
.Vector{D} where D <: (Dict{String, T} where T)
describes all vectors where the elements are dictionaries with string keys. The type varD
can match any dictionary type where the keys are strings, includingDict{String, T} where T
orDict{String, Int}
.
您可以使用速记符号更简单地表达这一点:
You can express this much more simply with the shorthand notation:
function bbb(a::Vector{<: Dict{String, <: Any}})
println(a)
end
这篇关于julia 0.6中不同类型字典的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!