julia - 方法将不匹配嵌套类型限制

标签 julia dispatch

我有这个简单的方法来计算向量集合的加权平均值

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/

相关文章:

io - 如何在 Julia 分布式 for 循环中以非交互方式执行 I/O?

arrays - 如何在Julia中定义DataFrames的空数组?

python - win32com.client.Dispatch 有效但 win32com.client.gencache.EnsureDispatch 无效

ios - dispatch_after 还是 NSTimer?

ios - 无法在 Swift 中使用范围方法之外的变量(dataTaskWithRequest)

multithreading - Julia 中线性回归的并行/多线程版本

DataFrames.jl - 按类型或名称子字符串选择列

julia - 如何快速 reshape 数组

javascript - 我在哪里可以找到好的 D3 事件和调度示例?

c++ - Qt Ctrl++(Control Plus Plus)快捷方式在 Qt 5.5 中不起作用