## An unusual definition of total ordering

One of the things that will show up in the imminently forthcoming Scala 2.7.1 release candidate, is the addition of traits for representing equivalence relations, partial orderings, and total orderings. Previously, the trait

was used for representing totally ordered things:

Ordered

trait Ordered[A] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 def compareTo(that: A): Int = compare(that) }

However, the

trait does not provide a representation of a total ordering. Therefore, the new trait

Ordered

`Ordering`

:

trait Ordering[T] extends PartialOrdering[T] { def compare(x: T, y: T): Int override def lteq(x: T, y: T): Boolean = compare(x, y) <= 0 override def gteq(x: T, y: T): Boolean = compare(x, y) >= 0 override def lt(x: T, y: T): Boolean = compare(x, y) < 0 override def gt(x: T, y: T): Boolean = compare(x, y) > 0 override def equiv(x: T, y: T): Boolean = compare(x, y) == 0 }

The tricky part however, was writing description of the properties required of something that implements the

trait. When one normally thinks of a total ordering one thinks of a relation that is

Ordering

- anti-symmetric,
- transitive,
- and total.

The problem is that

is not defined in terms of a binary relation, but a binary function producing integers (

Ordering

). If the first argument is less than the second the function returns a negative integer, if they are equal in the ordering the function returns zero, and if the second argument is less than the first the function returns a positive integer. Therefore, it is not straightforward to express these same properties. The best I could come up with was

compare

, for any- compare(x, x) == 0

of type- x

.- T

and- compare(x, y) == z

then- compare(y, x) == w

, for any- Math.signum(z) == -Math.signum(w)

and- x

of type- y

and- T

and- z

of type- w

.- Int

- if

and- compare(x, y) == z

and- lteq(y, w) == v

and- Math.signum(z) >= 0

then- Math.signum(v) >= 0

and- compare(x, w) == u

,- Math.signum(z + v) == Math.signum(u)

for any

,- x

, and- y

of type- w

and- T

,- z

, and- v

of type- u

.- Int

Where

returns

Math.signum

if its input is negative,

-1

if its input is

0

, and

0

if its input is positive.

1

The first property is clearly reflexivity. I call the third property transitivity. I am not sure what to call the second property. I do not think a notion of totality is required because it is assumed you will always get an integer back from

rather than it throwing an exception or going into an infinite loop.

compare

It would probably be a good exercise to prove that given these properties on

hold if and only if

compare

(defined above in terms of

lteq

) has all the normal properties of a total ordering.

compare