I have been recently using julia and I want to know what the “proper” way of overloading operators is.
Right now whwat I’m doing is defining a module and, inside that module i have basically the following:
import Base : +,-,*,/ .....
function +(x::MyStruct, y::MyStruct)
And then for each operator I want to define in addition to implementing the method I have to remember to modify what I import and export from my module.
Is there a cleaner way to do this?
function Base.:+(x::MyStruct, y::MyStruct)
export required. (
export is not required in any case, because
Base exports are already visible to any caller.) This idiom has the added benefit that it is clear at the function-definition site that you are modifying a
Note that it is
Base.+, to distinguish it from a call
Base .+ (...) to
This seems much more sensible, thanks!
Quick question though, what does the
: do at
Base.:+ exactly? I understand that it is to disambiguate from a call to the broadcasted
+ but how does it prevent it? Is the
+ function actually defined in Base as
: is used to “quote” symbols after
., it is part of the syntax (cf quoting for symbols, eg
:b). It is not necessary, but you could quote eg
sum (generic function with 13 methods)