Overloading a function in two files (in Julia)

I will explain my problem with a minimal example. Let's say I have three files:

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

      

Main.jl

 using A
 using B

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

 main()

      

Here I have two versions of the function f

. If I understand the idea of ​​multiple dispatches correctly, it should be subtracted at runtime which version to use. Hence, I expected that running Main.jl would print f called with A

. Sorry I am getting

$ 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

      

If I comment using B

, it works great. It is clear that f

from B.jl is rewritten f

from A.jl.

So the question is: where is the problem? In my approach or in the Julia version am I using (0.3.7)? How can I get around this?

Note that replacing using A

with import A

and using fully qualified names (eg A.f

) is not a good solution. This is contrary to the essence of multiple dispatch - at compile time I don't know if I should use A.f

or B.f

.

+3


source to share


1 answer


You have to make A.f

and B.f

the same function (in the example above, it's just different functions with the same name). Then you can overload one method in each of the modules and multiple dispatch will do its job.

To achieve this, either you need one of the modules to import a function f

from another (for example, import A.f

into B

) before extending it with a new method, or adding a third module C

with a function f

that imports both A

and B

(you can use a dummy type signature f(::Union()) = nothing

that never does not apply to create a function without adding any real method). Our function is distributed directly from another module, as in



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

      

This will make Julia realize that the two f

refer to the same concept and they will actually be the same object in both modules. Adding a method changes the overall functional object, so this change will appear wherever it is used f

.

+5


source







All Articles