How to overload the ==?

question

#1

I defined the Base.isequal function, but it do not work.

               _       
   _       _ _(_)_     |  A fresh approach to technical computing            
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org          
   _ _   _| |_  __ _   |  Type "?help" for help.                             
  | | | | | | |/ _` |  |                      
  | | |_| | | | (_| |  |  Version 0.5.2 (2017-05-06 16:34 UTC)               
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release             
|__/                   |  x86_64-pc-linux-gnu 

julia> type Foo foo::Int end                  

julia> type Bar bar::Float64 end              

julia> f = Foo(4)      
Foo(4)                 

julia> b = Bar(4.0)    
Bar(4.0)               

julia> function Base.isequal(a::Foo, b::Bar)  
           Float64(a.foo) == b.bar            
       end             

julia> isequal(f, b)   
true                   

julia> f == b          
false                  

#2

isequal falls back to ==

julia> @code_lowered isequal(f, b)
CodeInfo(:(begin 
        nothing
        return x == y
    end))

you can do Base.:(==)(a::Foo, b::Bar) = ...

see https://docs.julialang.org/en/stable/stdlib/base/#Base.isequal-Tuple{Any,Any} for more info


#3

Thanks, this works.

I need to redefine Base.:(==) separately to make == work.


#4

you likely don’t have to touch isequal at all, unless you want it to behave differently from ==.