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

查看:17
本文介绍了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 描述了所有带有字符串键的字典.类型 var T 可以匹配任何类型,包括 AnyInt.
  • 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} where T} 描述了一个向量,其中元素类型是exactly Dict{String, T} where T.参数不变性意味着 Vector{Dict{String, Int}}not 的子类型 Vector{Dict{String, T} where T}.
  • Vector{D} where D <: (Dict{String, T} where T) 描述所有向量,其中元素是带有字符串键的字典.类型 var D 可以匹配任何键为字符串的字典类型,包括 Dict{String, T} where TDict{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

这篇关于julia 0.6中不同类型字典的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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