茱莉亚0.6中不同类型的字典的向量 [英] Vector of dictionaries of different types in julia 0.6

查看:45
本文介绍了茱莉亚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 描述所有带有字符串键的字典.类型var T 可以匹配任何类型,包括 Any Int .
  • Dict{String, Any} describes a dictionary where the keys are strings and the value type is exactly Any. Parametric invariance means that Dict{String, Int} is not a subtype of Dict{String, Any}.
  • Dict{String, T} where T describes all dictionaries with string keys. The type var T can match any type, including Any or Int.

现在,当您开始谈论字典向量时,适用相同的原理:

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)描述所有向量,其中元素是带字符串键的字典.var D 类型可以匹配键为字符串的任何字典类型,包括 Dict {String,T},其中T Dict {String,Int} .
  • Vector{Dict{String, T} where T} describes a vector where the element type is exactly Dict{String, T} where T. Parametric invariance means that Vector{Dict{String, Int}} is not a subtype of Vector{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 var D can match any dictionary type where the keys are strings, including Dict{String, T} where T or Dict{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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆