2024-12-21

Order Type Class

Notes
This article was translated by GPT-5.2-Codex. The original is here.

Order

Order is a type class that represents total ordering.

Cats' Order is defined as a trait with a compare method.

1
trait Order[@sp A] extends Any with PartialOrder[A] { self =>
2
3
def compare(x: A, y: A): Int
4
5
def comparison(x: A, y: A): Comparison = Comparison.fromInt(compare(x, y))
6
7
def partialCompare(x: A, y: A): Double = compare(x, y).toDouble
8
9
def min(x: A, y: A): A = if (lt(x, y)) x else y
10
11
def max(x: A, y: A): A = if (gt(x, y)) x else y
12
13
override def eqv(x: A, y: A): Boolean =
14
compare(x, y) == 0
15
16
override def neqv(x: A, y: A): Boolean = !eqv(x, y)
17
18
override def lteqv(x: A, y: A): Boolean =
19
compare(x, y) <= 0
20
21
override def lt(x: A, y: A): Boolean =
22
compare(x, y) < 0
23
24
override def gteqv(x: A, y: A): Boolean =
25
compare(x, y) >= 0
26
27
override def gt(x: A, y: A): Boolean =
28
compare(x, y) > 0
29
30
def toOrdering: Ordering[A] =
31
compare(_, _)

All methods other than compare are default implementations that rely on compare. In the Cats type class diagram, PartialOrder is not highlighted, so I looked at Order first. However, you must still know what PartialOrder requires to implement. PartialOrder requires partialCompare, but Order can implement partialCompare and eqv via compare, so if you can define compare for Order, it can also serve as instances of Eq and PartialOrder.

Unlike Eq.fromUniversalEquals, there doesn’t seem to be a method that returns an Order instance just by calling it, so you must define the instance yourself or use derives.

Loading code...

To derive instances with derives, all fields must already have Order instances defined.

If you know the mathematical definition of total order, there is nothing particularly noteworthy about Order. However, partial order (PartialOrder) is a concept taught in discrete math (not in high school math, I guess), so it might be unfamiliar to those who haven't studied university math. That might be why it isn't highlighted.

Order syntax

Type ClassSyntaxDescription
OrdercompareCompares left and right; returns a negative value if left is smaller, positive if larger, 0 if equal.
OrderminReturns the smaller of left and right.
OrdermaxReturns the larger of left and right.
OrdercomparisonReturns Comparison, equivalent to Haskell's Ordering.
PartialOrder>Returns true if left is greater than right.
PartialOrder>=Returns true if left is greater than or equal to right.
PartialOrder<Returns true if left is less than right.
PartialOrder<=Returns true if left is less than or equal to right.
PartialOrderpartialCompareSame as compare.
PartialOrderpartialComparisonSame as Comparison.