这就是我在Julia中看到的最简单的多次调度示例 - 它是一个名为adhoc.jl的文件的整个(8行)内容.
f = function(x::String)
println("Called first version of f")
end
f = function(x::Float64)
println("Called second version of f")
end
f("x")
f(1.0)
Run Code Online (Sandbox Code Playgroud)
然而,当我运行那个(通过include("Adhoc.jl"))julia抱怨:
ERROR: LoadError: MethodError: no method matching
(::getfield(Main, Symbol("##17#18")))(::String)
Run Code Online (Sandbox Code Playgroud)
截图在这里
如果我改变的第二个实例f来g工作上的事情,但是这不再利用多分派.为什么我不能通过多次发送到达一垒?
Bog*_*ski 13
这是更正后的版本:
function f(x::String)
println("Called first version of f")
end
function f(x::Float64)
println("Called second version of f")
end
f("x")
f(1.0)
Run Code Online (Sandbox Code Playgroud)
您的代码的问题是您的原始代码创建了一个匿名函数并将其分配给变量f.你做了两次,因此f只指向function(x::Float64).
您可以通过在Julia REPL中运行原始代码来查看问题:
julia> f = function(x::String)
println("Called first version of f")
end
#3 (generic function with 1 method)
julia> f = function(x::Float64)
println("Called second version of f")
end
#5 (generic function with 1 method)
julia> methods(f)
# 1 method for generic function "#5":
[1] (::getfield(Main, Symbol("##5#6")))(x::Float64) in Main at REPL[2]:2
Run Code Online (Sandbox Code Playgroud)
你会看到f一个只有一个方法的匿名函数的点.
运行我的代码(您需要重新启动Julia REPL作为f变量名称,并且无法重新分配):
julia> function f(x::String)
println("Called first version of f")
end
f (generic function with 1 method)
julia> function f(x::Float64)
println("Called second version of f")
end
f (generic function with 2 methods)
julia> f("x")
Called first version of f
julia> f(1.0)
Called second version of f
julia> methods(f)
# 2 methods for generic function "f":
[1] f(x::Float64) in Main at REPL[2]:2
[2] f(x::String) in Main at REPL[1]:2
Run Code Online (Sandbox Code Playgroud)