Multiple dispatch with module and external functions

Hello everyone,

Julia newbie here. My problem revolves around multiple dispatch. The following is a pseudo-code and might not adhere to the proper syntax.

custom_module.jl

module custom_module

export Residual
export geterror!
export solve

abstract type Residual end

function geterror!(res::T) where {T<: Residual}
  println("In base function method")
end

function solve(res::T) where {T <: Residual}
     geterror!(res)
end

end

test.jl

using custom_module

mutable struct MutatedResidual <: Residual
end

function geterror!(res::MutatedResidual)
  println("In mutated residual")
end

solve(MutatedResidual())

The expectation is that the function with MutatedResidual argument is called. Instead the base method within the module is called. One option to solve this is to do geterrror!(res::T) where {T<:Residual} = geterrror!(res::MutatedResidual). However, if I have multiple mutations of Residual with each having its own overloaded version of geterror! then each assignment geterrror!(res::T) where {T<:Residual} = geterrror!(res::MutatedResidual) will override the previous one. Basically, I want to be able to do multiple dispatch by exposing the functions outside the module to the module so that it calls the appropriate functions (as determined by the type of the argument).

If the details are unclear, I am happy to provide more details. Also, if I am violating community guidelines with the format/nature/content of the question, please do critique.

I think that to add methods to the function of the module you need to explicitly import it:

import custom_module.geterror
geterror(res::MutatedResidual) = ...
1 Like

That is correct. But I have multiple definitions of geterror! for different arguments and assigning a version of geterror! will override any previous assignments. However, I want custom_module to see all the variants of geterror! not just the one assigned, so that solve can call appropriate versions.

I think that will work as you expect, if you add a method to the function for the new types you defined. I mean exactly as in your example but importing the function before defining the method. I think that works. Sorry not being able to test it now.

An alternative is to add the method explicitly to the module function:

custom_module.geterror(res::MutatedResidual) = ...

That should work as well.

Apologies. I had a typo. import cumstom_module.geterror! does the job. Thank you @lmiq. I need to faimiliarize myself with the intricacies of using and import.

1 Like