Search code examples
julia

overwriting + function with custom function in Julia


I try to implement a custom addition (and substraction) function in Julia for created types

import Base: *, +, -

function +(in1::MyType,in2::MyType)
    if condition_met
        return 2*in1
    else
        return in1 + in2
    end
end

-(in1::MyType,in2::MyType) = in1 + -1*in2

that works fine for the case when the condition is met, but of course it leads to an infinite loop for the case when the condition is not met (since it will invoke the function again). Is there an (elegant) way to circumvent this problem?


Solution

  • Here's an example implementation

    struct MyType
        val::Float64
    end
    
    function Base.:+(x::MyType, y::MyType)
        if x.val > 100
            return MyType(2 * x.val)
        else
            return MyType(x.val + y.val)
        end
    end
    Base.:-(x::MyType) = MyType(-x.val)
    Base.:-(x::MyType, y::MyType) = x + (-y)
    

    Using it:

    julia> x = MyType(2.0)
    MyType(2.0)
    
    julia> y = MyType(3.0)
    MyType(3.0)
    
    julia> z = MyType(103.0)
    MyType(103.0)
    
    julia> x + y
    MyType(5.0)
    
    julia> x - y
    MyType(-1.0)
    
    julia> z + y
    MyType(206.0)
    
    julia> y + z
    MyType(106.0)