In computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy.
Many processors have instruction sets that support such an operation on primitive types. Some machines have signed integers based on a sign-and-magnitude or one's complement representation (see signed number representations), both of which allow a differentiated positive and negative zero. This does not violate trichotomy as long as a consistent total order is adopted: either −0 = +0 or −0 < +0 is valid. Common floating point types, however, have an exception to trichotomy: there is a special value "NaN" (Not a Number) such that x < NaN, x > NaN, and x = NaN are all false for all floating-point values x (including NaN itself).
In C, the functions strcmp
and memcmp
perform a three-way comparison between strings and memory buffers, respectively. They return a negative number when the first argument is lexicographically smaller than the second, zero when the arguments are equal, and a positive number otherwise. This convention of returning the "sign of the difference" is extended to arbitrary comparison functions by the standard sorting function qsort
, which takes a comparison function as an argument and requires it to abide by it.
In Perl (for numeric comparisons only), PHP (since version 7), Ruby, and Groovy, the spaceship operator <=>
returns the values −1, 0, or 1 depending on whether A < B, A = B, or A > B, respectively. In Python 2.x (removed in 3.x), the cmp
function computes the same thing. In OCaml, the compare
function computes the same thing. In the Haskell standard library, the three-way comparison function compare
is defined for all types in the Ord
class; it returns type Ordering
, whose values are LT
(less than), EQ
(equal), and GT
(greater than):