我试图理解 Julia 类型图中数组的结构。这对我来说似乎非常违反直觉:
julia> Int64 <: Number
true
julia> Array{Int64,1} <: Array{Number,1}
false
julia> Array{Int64,1} <: Array{Int,1}
true
看来a <: b
不足以 Array{a,1} <: Array{b,1}
。 Array{a,1} <: Array{b,1}
什么时候?
一个实用的推论:如何类型声明一个抽象的数字数组?
最佳答案
在手册的下一页中,描述了 Julia 的类型如何保持不变而不是协变。 https://docs.julialang.org/en/v1/manual/types/#Parametric-Composite-Types-1
特别请参阅警告说明
This last point is very important: even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}.
并给出以下解释
In other words, in the parlance of type theory, Julia's type parameters are invariant, rather than being covariant (or even contravariant). This is for practical reasons: while any instance of Point{Float64} may conceptually be like an instance of Point{Real} as well, the two types have different representations in memory:
Point{Float64} 的实例可以紧凑而高效地表示为一对直接的 64 位值;
Point{Real} 的实例必须能够保存任意一对 Real 实例。由于作为 Real 实例的对象可以具有任意大小和结构,因此实际上 Point{Real} 的实例必须表示为一对指向单独分配的 Real 对象的指针。
具有任何类型数字的抽象数组都表示为这样
AbstractArray{<:Number}
这是 AbstractArray{T} where T <: Number
的缩写
关于julia - Julia 类型图如何处理数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61038884/