On this page:
<
>
<=
>=
compares_  equal
compares_  unequal
Comparable
8.12

6.41 Comparables🔗ℹ

A comparable value is one that supports <, <=, >=,>=, compares_equal, and compares_unequal. Real numbers, characters, strings, byte strings, symbols, and keywords are all comparable, as are instances of classes that implement Comparable.

operator

operator ((v1 :: Comparable) < (v2 :: Comparable)) :: Boolean

 

operator

operator ((v1 :: Comparable) > (v2 :: Comparable)) :: Boolean

 

operator

operator ((v1 :: Comparable) <= (v2 :: Comparable)) :: Boolean

 

operator

operator ((v1 :: Comparable) >= (v2 :: Comparable)) :: Boolean

 

operator

operator ((v1 :: Comparable) compares_equal (v2 :: Comparable))

  :: Boolean

 

operator

operator ((v1 :: Comparable) compares_unequal (v2 :: Comparable))

  :: Boolean

Compares v1 and v2, which uses a primitive comparison operation for real numbers, characters, strings, byte string, symbols, and keywords, or it calls the compare_to method for a Comparable instance.

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.

> 1 < 2

#true

> "apple" <= "banana"

#true

> #'banana >= #'apple

#true

> #'~banana > #'~apple

#true

> use_static

> 1 < "apple"

<: incompatible specializations from arguments (based on static information)

Provided only in the class space and annot space, not the namespace space.

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:

class Posn(x, y):

  private implements Comparable

  private override method compare_to(other :: Posn):

    let delta = x - other.x

    if delta == 0

    | y - other.y

    | delta

> Posn(1, 2) < Posn(2, 1)

#true

> Posn(1, 2) < Posn(1, 3)

#true

> Posn(1, 2) < Posn(1, 0)

#false