gpt4 book ai didi

Julia 无法进行多重分派(dispatch)

转载 作者:行者123 更新时间:2023-12-01 09:47:07 26 4
gpt4 key购买 nike

v06我想写一个需要 2 到 3 个参数的签名。第一个是整数或整数向量。第二个是整数向量或整数矩阵。第三个是整数向量或未指定。

第一次尝试是这样的

function foo(
a::Union{Integer, Vector{Integer}},
b::Union{Vector{Integer}, Matrix{Integer}},
c::Union{Void, Vector{Integer}} = nothing)

当我这样调用它时 foo(3, [0o7, 0o5])我收到一条错误消息,告诉我它无法匹配。

ERROR: LoadError: MethodError: no method matching foo(::Int64, ::Array{UInt8,1})
Closest candidates are:
foo(::Union{Array{Integer,1}, Integer}, !Matched::Union{Array{Integer,1}, Array{Integer,2}}) at ...
foo(::Union{Array{Integer,1}, Integer}, !Matched::Union{Array{Integer,1}, Array{Integer,2}}, !Matched::Union{Array{Integer,1}, Void}) at ...

现在我明白为什么 julia 无法匹配这个 Array{UInt8} <: Array{Integer} == false ,但这似乎只是 Julia 的不聪明。

然后我试了一下

foo(a::Union{Z1, Vector{Z1}},
b::Union{Vector{Z2}, Matrix{Z2}},
c::Union{Void, Vector{Z3}} = nothing
) where {Z1 <: Integer, Z2 <: Integer, Z3 <: Integer}

现在 julia 甚至不告诉我什么不匹配!

ERROR: LoadError: MethodError: no method matching foo(::Int64, ::Array{UInt8,1}, ::Void)
Closest candidates are:
foo(::Union{Array{Z1<:Integer,1}, Z1<:Integer}, ::Union{Array{Z2<:Integer,1}, Array{Z2<:Integer,2}}, ::Union{Array{Z3<:Integer,1}, Void}) where {Z1<:Integer, Z2<:Integer, Z3<:Integer} at ...
foo(::Union{Array{Z1<:Integer,1}, Z1<:Integer}, ::Union{Array{Z2<:Integer,1}, Array{Z2<:Integer,2}}) where {Z1<:Integer, Z2<:Integer} at ...

最佳答案

是的,Array{UInt8} <: Array{Integer} == false .这称为“参数不变性”。许多其他问题都讨论了这个话题。

但是,您遇到的另一个问题是,当您使用静态函数参数时 — 即 f(…) where TT 必须 匹配某些东西,因为它可以在函数体中使用。这会在 Union 中引起麻烦T在哪里并非在每个选项中都可用。我相信关于更改此行为以允许匹配 Union 存在一个悬而未决的问题不包含 T 的元素,如果您尝试访问该绑定(bind),它将将该绑定(bind)转换为 undefined variable 。

现在的解决方法是使用不是函数静态参数的类型变量。例如,

   foo(a::Union{Integer, Vector{<:Integer}},
b::Union{Vector{<:Integer}, Matrix{<:Integer}},
c::Union{Void, Vector{<:Integer}} = nothing) = 1

关于Julia 无法进行多重分派(dispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46366901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com