茱莉亚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},其中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}其中T}
描述了一个向量,其中元素类型完全是Dict {String,T}其中T 代码>.参数不变性意味着
Vector {Dict {String,Int}}}
不是Vector {Dict {String,T}的子类型,其中T}
-
Vector {D},其中D< :( Dict {String,T},其中T)
描述所有向量,其中元素是带字符串键的字典.varD
类型可以匹配键为字符串的任何字典类型,包括Dict {String,T},其中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
这篇关于茱莉亚0.6中不同类型的字典的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!