Overloading operators

Hello,

How I can oveload base operators in Julia ?

Thanks

2 Likes

To extend a method from Base you need to import it first. To import the method fun you can use either import Base.fun or import Base: fun. The second is a bit easier if you want to import multiple methods. Then you can define a new method for your type with the normal syntax fun(a::YourType) = somethingnew.

2 Likes

Operators can be defined just like normal functions. For example

import Base.+

struct TestType end

(+)(::TestType, ::Void) = nothing
6 Likes

Not necessarily: qualifying with package names also works. Eg

Base.:+(x::SomeType, y::SomeType) = ...

Note the quote (:) before the +.

10 Likes

I write this code to oveload this operator >= .

julia>import Base;
julia> Base.:>=(a::JuMP.Variable,b::Float64) = (a >= b)

julia> temp_in >=9.00

But I still have this error :sweat:

ERROR: MethodError: no method matching isless(::Float64, ::JuMP.Variable)
Closest candidates are:
  isless(::Float64, ::Float64) at float.jl:439
  isless(::PyCall.PyObject, ::Any) at /home/monpc/.julia/v0.6/PyCall/src/pyoperators.jl:71
  isless(::AbstractFloat, ::AbstractFloat) at operators.jl:96
  ...
Stacktrace:
 [1] >=(::JuMP.Variable, ::Float64) at ./REPL[138]:1

How I can resolve it ?

Look at the signature in the error: you did the wrong one. Flip the order.

6 Likes

In case anyone is looking to overload == and finds this post, you can do so with

Base.:(==)(a::MyType, b::MyType) = ...

When trying to do Base.:== from the REPL, it doesn’t evaluate (expecting more input), and from a script, I get the confusing message

LoadError: syntax: type declarations on global variables are not yet supported

Note this is for Julia 1.6.3, I don’t know if this has changed in recent history.

3 Likes
import Base: ==, +, -, *, /, \, inv, ^, <, <=, <<, >>, %, ÷

struct DFP{N} <: Real
    s::Int8
    expo::BigInt
    m::Array{Int8,1}
end


+(x::DFP{N}, y::DFP{N}) where {N} = DFP_add(x,y)