Pair of methods for symmetric operator by a single definition

Hi, I’ve been trying to familiarize myself with Julia lately and I finally stumbled upon a question to which I couldn’t find an answer yet, so I signed up to Discourse :slight_smile:

First of all, thanks to everyone who contributed creating the enjoyable learning atmosphere around the Julia language!

And here goes my question:

julia> struct myInt i::Int end

julia> Base.:(==)(int::Int, my::myInt) = int == my.i

julia> m = myInt(1)

julia> 1 == m
true

julia> m == 1
false

Is there a way to mark the definition of the (==)method as symmetric if you want to implement a symmetric operator? Then the compiler could create all permuted signatures of the method, instead of having to write them out by hand.

PS: Not using promotion mechanism on purpose here.

No. Typically you just define (update: fixed typo)

Base.:(==)(my::myInt, int::Int) = int == my

(Alternatively, you define a promote_rule to promote them both to myInt, and then define a single == rule for two myInt. Promotion rules are automatically symmetrized.)

2 Likes

Nitpick, but presumably you meant int == my.