Overloading operators

question

#1

Hello,

How I can oveload base operators in Julia ?

Thanks


#2

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.


#3

Operators can be defined just like normal functions. For example

import Base.+

struct TestType end

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

#4

Not necessarily: qualifying with package names also works. Eg

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

Note the quote (:) before the +.


#5

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 ?


#6

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