【问题标题】:Difference between `where` keyword inside or outside the curly braces`where` 关键字在花括号内部或外部的区别
【发布时间】:2020-11-09 17:01:40
【问题描述】:

有什么区别

function foo(a::Adjoint{Float64, Matrix{T}} where T)
    return 0
end

function foo(a::Adjoint{Float64, Matrix{T} where T})
    return 1
end

(注意花括号的位置。)

julia> methods(foo)
# 2 methods for generic function "foo":
[1] foo(a::Adjoint{Float64,Array{T,2}} where T) in Main at REPL[247]:2
[2] foo(a::Adjoint{Float64,Array{T,2} where T}) in Main at REPL[248]:2

似乎在这两种情况下,该函数都会接受T 类型的矩阵的伴随?我不知道这两个函数有什么区别。

【问题讨论】:

  • 嗯,其中一个返回0,另一个返回1 =P

标签: julia where-clause


【解决方案1】:

第一个是unionall类型,第二个是具体类型:

julia> isconcretetype(Adjoint{Float64, Matrix{T} where T})
true

julia> isconcretetype(Adjoint{Float64, Matrix{T}} where T)
false

julia> (Adjoint{Float64, Matrix{T}} where T) isa Core.UnionAll
true

第一个是无限的伴随集合,包裹着某种类型的Matrix。换句话说,我们可以想象用伪代码表示无限集:

Set([Adjoint{Float64, T} for T in all_possible_types])

而第二个是包含某种类型的Matrix 的伴随,或者换句话说:

Adjoint{Float64, Matrix_of_any_type}.

您几乎总是想要前者,而不是后者。几乎没有理由构造一个可以包含任何Matrix 的伴随词,通常你只需要一个类型的伴随词。

Vector 的区别更明显:

  • Vector{Vector{T}} where T 是一个 unionall,表示所有同类型向量的向量。
  • Vector{Vector{T} where T} 是包含特定元素类型Vector{T} where T 的向量。

【讨论】:

【解决方案2】:

下面是一个示例,说明了 Vector{Vector{T} where T}Vector{Vector{T}} where T 的简单情况的区别。

先做一些类型别名:

julia> const InsideWhere = Vector{Vector{T} where T}
Array{Array{T,1} where T,1}

julia> const OutsideWhere = Vector{Vector{T}} where T
Array{Array{T,1},1} where T

如果可能,默认数组构造函数会将元素提升为通用类型:

julia> x = [[1, 2], [1.2, 3.4]]
2-element Array{Array{Float64,1},1}:
 [1.0, 2.0]
 [1.2, 3.4]

julia> x isa InsideWhere
false

julia> x isa OutsideWhere
true

但是通过使用typed array literal,我们可以避免自动升级:

julia> y = ( Vector{T} where T )[[1, 2], [1.2, 3.4]]
2-element Array{Array{T,1} where T,1}:
 [1, 2]
 [1.2, 3.4]

julia> y isa InsideWhere
true

julia> y isa OutsideWhere
false

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2013-11-02
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2020-11-17
    • 2014-01-24
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多