我有这个简单的方法来计算向量集合的加权平均值
function meanw{T <: Number}(x::AbstractArray{AbstractVector{T}, 1}, w::AbstractVector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
但是当我尝试使用它时,调度无法匹配我的方法。
ERROR: `meanw` has no method matching meanw(::Array{Array{Float64,1},1}, ::Array{Float64,1})
我怀疑我误解了在涉及嵌套时如何使用类型限制。我应该如何重写这个函数来匹配我的收藏?
附言
我知道向量和数组是一回事,但是区别使函数的使用方式更加清晰。
最佳答案
因此,如果您重写代码以使用具体的类型,它就可以工作
function meanw{T <: Number}(x::Array{Vector{T}, 1}, w::Vector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
这也有效
function meanw{T <: Number}(x::Array{Vector{T}, 1}, w::AbstractVector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
这不起作用
function meanw{T <: Number}(x::Array{AbstractVector{T}, 1}, w::AbstractVector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
这确实再次起作用
function meanw{T <: Number}(x::AbstractArray{Vector{T}, 1}, w::AbstractVector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
我们在这里遇到的问题在 Julia 手册中的 parametric types 下进行了描述。
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:
真正起作用的是这个
function meanw{T <: Number, V <: AbstractVector}(x::AbstractArray{V, 1}, w::AbstractVector{T})
x̄ = sum(x .* w)
x̃ = map(z -> z - x̄, x)
x̄, x̃
end
但真正的问题是你为什么要这样做?
Julia 编译器足够聪明,即使没有类型注释,只要输入类型良好且函数本身类型稳定,就可以生成高效代码。类型注释仅在多次调度时才真正需要,并且作为契约(Contract)来指定函数实际可以处理的内容,但由于广泛的类型系统,这在 Julia 中是出了名的困难。
关于julia - 方法将不匹配嵌套类型限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25490364/