I have defined the operator < for my custom type Person:
begin
struct Person
name::String
age::Int
end
import Base: <
function <(a::Person, b::Person)::Bool
return a.age < b.age
end
# Example usage
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
println(person1 < person2) # This will print "false" because 30 is not less than 25
println(person2 < person1) # This will print "true" because 25 is less than 30
# ---- inference ??????
println(person2 > person1) # This will print "false" because 25 is less than 30
end
In my last println, it seems that Julia inferred how the > operator should behave for my custom type, even though I didnāt define it, which is great.
My question is, what is this mechanism called? (By āmechanismā, I mean the behavior where, if the user defines operator X, Julia generates code for operator Y, given that there is a relationship between X and Y.)
N.B.: Sorry for the horrible title; Iām not sure how to express this.
We often call these sorts of definitions āgenericā or āfallbackā implementations. Functions in Julia have a meaning ā and in some cases itās possible to define implementations for Any arguments based on other methods.
Ah, youāre right, it makes senseā¦ I also have just found in the docs:
Generally, new types should implement < instead of this function, and rely on the fallback definition >(x, y) = y < x.
EDIT: itās less impressive now, because I thought there is some sort of multiple dispatch mechanism that infers this, but itās actually just the implementation
Matter of perspective One could also find it impressive how easy it is to write generic, performant code. The default implementation in case implements > for all arguments exactly as fast as the hand-written counterpart < in a single line of code. Sure while this is an almost trivial example, it does still show the simplicity and power of Julia imo