From e36bbc82f2fc49945b4ef42ddeca8c1443c3bac4 Mon Sep 17 00:00:00 2001 From: "Havvy (Ryan Scheel)" Date: Mon, 3 Sep 2018 23:11:15 -0700 Subject: [PATCH] Example of total ord of elements for sort_by --- src/liballoc/slice.rs | 6 ++++++ src/libcore/slice/mod.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 2ded376b395a..ad47eb4b70bb 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -242,6 +242,12 @@ impl [T] { /// // reverse sorting /// v.sort_by(|a, b| b.cmp(a)); /// assert!(v == [5, 4, 3, 2, 1]); + /// + /// // While f64 doesn't implement Ord because NaN != NaN, we can use + /// // partial_cmp here because we know none of the elements are NaN. + /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0]; + /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap()); + /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index c22ea0a01f8e..a6e0389e66f1 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1367,6 +1367,12 @@ impl [T] { /// // reverse sorting /// v.sort_unstable_by(|a, b| b.cmp(a)); /// assert!(v == [5, 4, 3, 2, 1]); + /// + /// // While f64 doesn't implement Ord because NaN != NaN, we can use + /// // partial_cmp here because we know none of the elements are NaN. + /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0]; + /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); + /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]); /// ``` /// /// [pdqsort]: https://github.com/orlp/pdqsort