gpt4 book ai didi

julia - 在两个文件中重载一个函数(在 Julia 中)

转载 作者:行者123 更新时间:2023-12-01 01:48:41 27 4
gpt4 key购买 nike

我将用一个最小的例子来解释我的问题。假设我有三个文件:

A.jl

module A

export Atype, f

type Atype
end

f = function(x::Atype)
println("f called with A")
end
end #module

B.jl

module B

export Btype, f

type Btype
end

f = function(x::Btype)
println("f called with B")
end
end #module

主.jl

 using A
using B

main = function()
x = Atype()
f(x)
end

main()

这里我有两个版本的 f 函数。如果我正确理解多重分派(dispatch)的想法,应该在运行时扣除应该使用哪个版本。因此,我预计运行 Main.jl 会打印 f called with A。不幸的是,我得到了

$ julia Main.jl 
ERROR: type: anonymous: in typeassert, expected Btype, got Atype
in include at /usr/bin/../lib64/julia/sys.so
in process_options at /usr/bin/../lib64/julia/sys.so
in _start at /usr/bin/../lib64/julia/sys.so
while loading /home/grzes/julia_sucks/Main.jl, in expression starting on line 9

如果我注释掉 using B,它会正常工作。显然,B.jl 中的 f 覆盖了 A.jl 中的 f

那么,问题来了:问题出在哪里?在我的方法中还是在我使用的 Julia 版本 (0.3.7) 中?我怎样才能避免这种情况?

请注意,将 using A 替换为 import A 并使用完全限定名称(例如 A.f)并不是一个好的解决方案。它与多重分派(dispatch)的症结相矛盾——在编译时我不知道我应该使用 A.f 还是 B.f

最佳答案

您必须使 A.fB.f 成为相同的函数(在上面的示例中,它们只是具有相同名称的不同函数)。然后您可以在每个模块中重载一个方法,多个分派(dispatch)将完成它的工作。

实现这一点的方法是让其中一个模块从另一个模块导入函数 f(例如 import A.f in B ) 在用新方法扩展它之前,或者添加第三个模块 Cf 函数,AB import (你可以使用像 f(::Union()) = nothing 这样的虚拟签名,它永远不会在不添加任何真实方法的情况下创建一个函数)。我们直接从其他模块扩展功能,如

function A.f(x::Atype)
println("f called with A")
end

这将使 Julia 明白这两个 f 指的是同一个概念,它们实际上是两个模块中的同一个对象。添加方法会修改通用函数对象,因此在使用 f 的任何地方都可以看到此更改。

关于julia - 在两个文件中重载一个函数(在 Julia 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228282/

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