Description
The Rust standard library (rightly, in my view) distinguishes PartialOrd
(resp. -Eq
) from Ord
, primarily because according to their usual semantics, IEEE754 floating-point numbers do not have a total ordering, and therefore implement only the Partial
traits. So far, so good. However, beyond this point, when faced with common tasks involving floating-point types which would in fact require an implementation of Eq
or Ord
- such as sorting, minimum/maximum, binary search, using them as keys in a data structure, etc. - users are currently, to a large degree, left to figure things out on their own, often leading to pain and frustration on their part.
We could do something about this, and make their lives easier, by providing wrapper newtypes (single-field struct
s) over the floating-point types which do in fact implement Eq
and Ord
, according to various policies. I can think of several different possibilities off the top of my head, any of which may be useful:
- The IEEE standard allegedly does specify a total ordering which may be used, even if it is not the ordering which is implemented in hardware. A newtype could be used to select this alternative (total) ordering.
- Another newtype could simply guarantee the absence of NaNs via a smart constructor, and implement
Eq
andOrd
on this basis. (This is based on a suggestion by @shepmaster in an answer on StackOverflow.) - Another pair of newtypes could be used to specify that NaNs are to be treated as always less than, or always greater than any other number.
- Another newtype could implement comparison simply based on the two numbers' bit-patterns as if they were
u32
andu64
. This ordering is likely to bear no relationship to the numerical one, but may be appropriate if one wishes to use floating-point types as keys in a data structure, provided that it doesn't really matter what the ordering (resp. equality) is, as long as it's total and fast.
If these were available, the options for bridging the gap between f
{32
,64
} and Ord
would be more apparent to users, and they could select the appropriate policy for dealing with NaNs based on their needs.
(Of course, such functionality would likely benefit from prototyping on crates.io beforehand, but I don't think it's unreasonable to consider it a candidate for eventual inclusion in std
.)