julia - Julia 多重调度入门

标签 julia

在我看来,这是 Julia 中可以想象的最简单的多分派(dispatch)示例——它是名为 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)

然而,当我运行它时(通过 include("Adhoc.jl") ), Julia 提示道:
ERROR: LoadError: MethodError: no method matching 
(::getfield(Main, Symbol("##17#18")))(::String)

附截图here

如果我更改 f 的第二个实例至g一切正常,但这不再使用多次调度。为什么我不能通过多次调度到达一垒?

最佳答案

这是更正的版本:

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) .

您可以通过在 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指向一个只有一种方法的匿名函数。

运行我的代码(您需要重新启动 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

关于julia - Julia 多重调度入门,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52224047/

相关文章:

arrays - 如何在 Julia 中连接不同大小的向量?

julia - julia 如何知道要使用什么路径分隔符和根目录?

dictionary - 定义一个空的 Dict,其中值是抽象类型的子类型

bash - Julia 命令行魔法使一个命令等待下一个命令

scope - 在 if 语句中使用全局声明(Julia 代码)

types - 函数向输入参数添加维度时的类型稳定性问题

julia - 两组各有 2 个向量的散点图

julia - 无法弄清楚 Cumulants.jl 的简单用法

continuous-integration - Github 操作 CI : making PyCall aware of Julia ENV variables

jupyter-notebook - 在 Julia 中的 Jupyter Notebook 上从 GitHub 下载文件时出现失败的过程错误