Compare
type Comparable = class
def (>) (rhs : Self) : bool
def (<) (rhs : Self) : bool
def (>=) (rhs : Self) : bool
def (<=) (rhs : Self) : bool
Class is a contract. It does not exist during runtime and cannot be casted to, but is useful as a constraint on a generic type parameter.
Self
is the type of an instance on which a method is invoked.
type Char
def (>) @c (rhs : Char) : bool
def (<) @c (rhs : Char) : bool
def (>=) @c (rhs : Char) : bool
def (<=) @c (rhs : Char) : bool
is Comparable
Char
implements all four required methods, and is explicitly declared as belonging to the Comparable
class.
The @c
attribute means that the declaration represents an existing C function, or in our case an operator, supported by the C language.
type Compare = class
def compare (other : Self) : Ordering
def (>) (rhs : Self) =
let result = compare rhs
result == Ordering/Greater
def (>=) (rhs : Self) =
let result = compare rhs
result <> Ordering/Less
def (<) (rhs : Self) =
let result = compare rhs
result == Ordering/Less
def (<=) (rhs : Self) =
let result = compare rhs
result <> Ordering/Greater
is Comparable
Class Compare
provides comparison operators in exchange for implementing a single compare
method.
type (T1, T2) u v where T1 : Comparable
T2 : Comparable
def compare (other : Self) = when
u > other.u -> Ordering/Greater
u < other.u -> Ordering/Less
v > other.v -> Ordering/Greater
v < other.v -> Ordering/Less
else -> Ordering/Equal
is Compare
We extend a tuple of two items T1
and T2
that are Comparable
. u
and v
are the item names to use in methods. Tuple belongs to both Comparable
and Compare
classes.