重载两个文件中的函数(在Julia中)

grz*_*ześ 3 multiple-dispatch julia

我将以最小的例子解释我的问题.假设我有三个文件:

A.jl

module A

export Atype, f

type Atype  
end

f = function(x::Atype)
    println("f called with A")
end
end #module
Run Code Online (Sandbox Code Playgroud)

B.jl

module B

export Btype, f

type Btype  
end

f = function(x::Btype)
    println("f called with B")
end
end #module
Run Code Online (Sandbox Code Playgroud)

Main.jl

 using A
 using B

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

 main()
Run Code Online (Sandbox Code Playgroud)

这里我有两个版本的f功能.如果我理解正确的多次发送的想法,应该在运行时期间扣除应该使用哪个版本.因此,我预计运行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
Run Code Online (Sandbox Code Playgroud)

如果我发表评论using B,它就可以了.很明显,fB.jl从A.jl覆盖了f.

所以,问题是:问题出在哪里?在我的方法或Julia的版本中,我使用(0.3.7)?我怎么能绕过这个呢?

请注意,更换using Aimport A使用完全合格的名称(如A.f)是不是一个很好的解决方案.它与多次发送的关键点相矛盾 - 在编译时我不知道是否应该使用A.fB.f.

Toi*_*son 6

你必须制作A.fB.f使用相同的功能(在上面的例子中,它们只是具有相同名称的不同功能).然后你可以在每个模块中重载一个方法,多个调度将完成它的工作.

实现这一目标的方法是让其中一个模块f从另一个模块导入函数(例如import A.fin B),然后再使用新方法扩展它,或者添加第三个模块,C其中包含f两个AB导入的函数(可以使用虚拟签名)就像f(::Union()) = nothing从来没有适用于创建一个函数而不添加任何真正的方法).我们直接从其他模块扩展功能,如

function A.f(x::Atype)
    println("f called with A")
end
Run Code Online (Sandbox Code Playgroud)

这将使Julia明白两者f引用相同的概念,并且它们实际上是两个模块中的相同对象.添加方法会修改通用函数对象,因此在f使用的任何位置都可以看到此更改.