Julia Multiple Dispatch入门 [英] Getting started with Julia Multiple Dispatch
问题描述
在我看来,这是Julia中最简单的可想象的多重调度示例-它是名为adhoc.jl的文件的全部(8行)内容.
Here's what looks to me the simplest imaginable example of multiple dispatch in Julia - it's the entire (8 line) contents of a file called adhoc.jl.
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)
但是当我运行该命令时(通过include("Adhoc.jl")
),茱莉亚抱怨道:
and yet when I run that (via include("Adhoc.jl")
) julia complains:
ERROR: LoadError: MethodError: no method matching
(::getfield(Main, Symbol("##17#18")))(::String)
带有屏幕截图此处
如果我将f
的第二个实例更改为g
,则一切正常,但这不再使用多重调度.为什么我不能通过多次派遣到达一垒?
If I change that second instance of f
to g
things work, but that's no longer making use of multiple dispatch. How come I can't get to first base with multiple dispatch?
推荐答案
这是更正的版本:
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)
您的代码的问题是您的原始代码创建了一个匿名函数并将其分配给变量f
.而且您做了两次,因此f
仅指向function(x::Float64)
.
The problem with your code is that your original code created an anonymous function and assigned it to a variable f
. And you did it twice, thus f
pointed only at function(x::Float64)
.
通过在Julia REPL中运行原始代码,您可以看到问题所在:
You can see the problem with your original code by running it in 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
,您会看到f
指向一个只有一个方法的匿名函数.
and you see that f
points at an anonymous function which has only one method.
运行我的代码(您需要重新启动Julia REPL,因为f
变量名将已被使用,并且无法重新分配):
Running my code (you need to restart Julia REPL as f
variable name will be already taken and it cannot be reassigned):
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
这篇关于Julia Multiple Dispatch入门的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!