9.5 Comparables
A comparable value is one that supports <, <=, >=,>=, compares_equal, and compares_unequal. Real numbers, characters, strings, byte strings, symbols, keywords, and paths are all comparable, as are instances of classes that implement Comparable.
operator | ||
| ||
| ||
operator | ||
| ||
| ||
operator | ||
| ||
| ||
operator | ||
| ||
| ||
operator | ||
| ||
| ||
operator | ||
|
See also .<, .>, .<=, .>=, .=, and .!=, which are specific to numbers.
The difference between compares_equal and == is that the former uses Comparable while the latter uses Equatable. The results tend to be the same, but they are different in the case of numbers: two numbers are == only when they have the same exactness, but compares_equal corresponds to .=.
The use_static declaration constrains <, etc., to work only when the left-hand argument or right-hand argument has static information indicating that it satisfies Comparable. If both expressions provide static information, the Comparable specifications must be compatible: both identifying the same operation, or one specifying the generic Comparable operation.
The comparison implementations for Number arguments is is specialized like + for arguments with Flonum static information. That specialization does not mean that a Number argument combined with a Flonum argument will trigger an ambiguous-comparison error in static mode, however.
> 1 < "apple"
<: incompatible specializations from arguments (based on static information)
interface | |
An interface that a class can implement (publicly or privately) to make instances of the class work with <, >, etc. As an annotation, Comparable matches all comparable objects, not just instances of classes that publicly implement the Comparable interface.
The interface has one abstract method, compare_to, and six methods that use compare_to by default but can be individually overridden:
compare_to(other) —
the other value is the right-hand argument to a comparison, and it is always an instance of the same class or a subclass that inherits the same compare_to implementation. The result must be an integer: negative if the object is less than the other, positive if the object is greater than other, and zero if they are equal. less(other) —
takes the same kind of argument as compare_to, but returns a boolean to indicate whether the object is less than other, and with the further constraint that the two objects have the same less implementation. This is the method called to implement <, but the default implementation of this method uses compare_to. less_or_equal(other) —
like less, but for <=. greater(other) —
like less, but for >. greater_or_equal(other) —
like less, but for >=. compares_equal(other) —
like less, but for compares_equal. compares_unequal(other) —
like less, but for compares_unequal.
class Posn(x, y):
| delta