Module cmp

Module cmp 

Source
Expand description

Ordering and comparisons of IEEE 754 floating-point and other partially ordered types.

This module provides traits and functions for partial and total orderings, in particular of floating-point types. For primitive floating-point types, the following total ordering is provided via the CanonicalEq and CanonicalOrd traits:

$$-\infin<\cdots<0<\cdots<\infin<\text{NaN}$$

Note that both zero and NaN have more than one representation in IEEE 754 encoding. Given the set of zero representations $Z$ and set of NaN representations $N$, this ordering coalesces -0, +0, and NaNs such that:

$$ \begin{aligned} a=b&\mid a\in{Z},~b\in{Z}\cr[1em] a=b&\mid a\in{N},~b\in{N}\cr[1em] n>x&\mid n\in{N},~x\notin{N} \end{aligned} $$

These same semantics are used in the Eq and Ord implementations for the Total proxy.

The EmptyOrd trait provides a particular ordering for types with a notion of empty inhabitants. These inhabitants are considered incomparable, regardless of whether or not they are ordered with respect to PartialOrd and Ord. For example, None is the empty inhabitant of Option and so cannot be compared with EmptyOrd.

For floating-point types, NaNs are considered empty inhabitants. In this context, empty can be thought of as undefined, but note that empty inhabitants are unrelated to proxy constraints. Unlike the standard ordering traits, EmptyOrd forwards empty inhabitants in comparisons. For floating-point types, this importantly means that NaNs are forwarded consistently in comparisons.

§Examples

Comparing f64 values using a total ordering:

use core::cmp::Ordering;
use decorum::cmp::CanonicalOrd;
use decorum::NanEncoding;

let x = f64::NAN;
let y = 1.0f64;

let (min, max) = match x.cmp_canonical(&y) {
    Ordering::Less | Ordering::Equal => (x, y),
    _ => (y, x),
};

Computing a pairwise minimum that propagates NaNs with EmptyOrd:

use decorum::cmp;
use decorum::NanEncoding;

let x = f64::NAN;
let y = 1.0f64;

// `NaN` is considered an empty inhabitant in this ordering, so `min` is assigned `NaN` in this
// example, regardless of the order of parameters.
let min = cmp::min_or_empty(x, y);

Traits§

CanonicalEq
Total equivalence relation of IEEE 754 floating-point encoded types.
CanonicalOrd
Total ordering of IEEE 754 floating-point encoded types.
EmptyInhabitant
EmptyOrd
Defines an ordering for types that (may) have empty inhabitants.

Functions§

max_or_empty
Pairwise maximum for types that may have an empty inhabitant that is incomparable.
min_max_or_empty
Pairwise ordering for types that may have an empty inhabitant that is incomparable.
min_or_empty
Pairwise minimum for types that may have an empty inhabitant that is incomparable.