Redefinition of + with custom types delivers errors


#1

Hi folks,

I was trying to implement my own add function for my own data types but that seems to deliver errors that I can’t find the reason for. Just look at this example

type mine
    x :: Int8
    z :: Float64
    mine() = new()
end

function ++(U::mine, V::mine)
    w = mine()
    w.x = U.x + V.x
    w.z = U.z + V.z
    return w
end;

# define two instances of mine()
u = mine()
u.x = 1
u.z = 3.1416
v = mine()
v.x = 2
v.z = 2.7183

# add them up
u ++ v

> mine(3,5.8599)

# We succeeded :)

# Now with standard + instead of ++
# It's the exact same code with ++ replaced with + !

function +(U::mine, V::mine)
    w = mine()
    w.x = U.x + V.x
    w.z = U.z + V.z
    return w
end;

LoadError: error in method definition: function Base.+ must be explicitly imported to be extended
while loading In[5], in expression starting on line 1

…so adding a (working) new method for + yields an error and it can’t be used.

So what am I doing wrong? Any help will be greatly appreciated :slight_smile:

Best regards,

Ferran.


#2

Basically, if you want to extend a method defined in other module, you need to explicitly import or specify the module name when defining a new method. So, the following code will work as you expect:

type Mine
    x::Int8
    y::Float64
end

function Base.:+(a::Mine, b::Mine)
    return Mine(a.x + b.x, a.y + b.y)
end

#=
julia> Mine(0, 0) + Mine(1, 1)
Mine(1,1.0)

=#

EDIT

Another way is explicitly importing a method you want to extend from its module before defining a new method:

import Base: +

function +(a::Mine, b::Mine)
    return Mine(a.x + b.x, a.y + b.y)
end