Julia :where

来源:互联网 发布:简体转繁体软件 编辑:程序博客网 时间:2024/04/26 03:32

一、有where和无where区别

a  = Array{Array{T,1} where T,1}() # Vectorb  = Array{T where T,1}() # Any[0]a==b # truec =Array{Array{T where T,1} where T,1}() # Vector{Any}[0]a==c #truea==c很奇怪吧。感觉这个设计有些问题。

1、type

ty(a::T) where T = Array{Array{T,1},1} where T;ty2(a::T) where T  = Array{Array{T,1} where T,1};ty3(a::T) where T  =Array{Array{T,1},1};以上三者都不一样。具体如下:typeof(ty(6.0)) # UnionAlltypeof(ty2(6.0)) # DataTypetypeof(ty3(6.0)) # Array{Array{Float64,1},1}typeof(ty(6.0)) ==typeof(ty2(6.0)) # false

2、数据

f(a::T) where T = Array{Array{T,1},1}()  f2(a::T) where T  = Array{Array{T,1} where T,1}();typeof(f2(6.0)) #Array{Array{Float64,1},1}typeof(f2(6.0)) #Array{Array{T,1} where T,1},是一个类型typeof(f2(6.0))==typeof(f2(6.0)) # false

具体来看,关于f2(a::T) where T = Array{Array{T,1} where T,1}():

data =f2(6.0);# 只是一个类型push!(data,[4.0])# 元素1push!(data,["abc"]) # 元素2,可以不同于元素1

而至于f(a::T) where T = Array{Array{T,1},1}() :

temp =f(6.0)push!(temp,[6.0])push!(temp,["abc"]) #=>error!,只能放[Float64]类型。

上面的区别现在容易搞清楚了吧。

二、关于构造函数

在官方文档中,有以下举例:

struct SummedArray{T<:Number,S<:Number}           data::Vector{T}           sum::S           function SummedArray(a::Vector{T}) where T               S = widen(T)               new{T,S}(a, sum(S, a))           endend

当在Repl中运行以下,会报错。

SummedArray(Int32[1; 2; 3], Int32(6))

加一句,就可以运行:

SummedArray{T<:Number}(a::Vector{T},::T) =  SummedArray(a::Vector{T});

但是,不能加where T

SummedArray{T<:Number}(a::Vector{T},::T) =  SummedArray(a::Vector{T}) where T;# 不能在此加where T
原创粉丝点击