Cannot sort floats

You may be right but I don't see how that would work. Would you mind spelling it out?

Sorry for the noise. I haven't paid enough attention to the signature of sort_by_cached_key.
You could use the ordered_float crate though here:

use ordered_float::NotNan; // 1.0.2

fn main() {
    let mut fs = vec![
        11.0_f32, 7.0, 5.0, 3.14, 3.0, 2.7182, 2.0, 1.4142, 9.8, 100.0, 10.0,
    ];
    fs.sort_by_cached_key(|f| NotNan::new(*f).unwrap());
    println!("{:?}", fs);
}

playground linke

Although I'm not sure why you have to use sort_by_cached_key and not stick to sort_by.

Well, it's not necessary for Turing completeness, of course but it is imho almost always more convenient than spelling out the comparison.

@alice I'm disappointed that I could not at least a little bit convince you that this is not the right behavior. :frowning:

You can convince me at least a little bit that it would be useful to have a sort_by_fallible construction, but I will insist that having a provably infallible sorting function is important.

Okay, maybe I will change my opinion to: the default float should be ordered_float::NotNan because NaNs can go to hell. :slight_smile:

And if they refuse to, the program will all of a sudden blow up without programmer being informed preemptively.

By the way, another point to think of might be like this: some sorting algorithms are using the fact of total ordering. Some implementations of quicksort, for example, might simply loop indefinitely on some pair of elements for which (a < b == false) && (b < a == false). And again, we don't want programmer to guess if our implementation is indeed safe from something like this, do we?

2 Likes

If you want the IEEE total order that works well with sort_by_key (no need for sort_by_cached_key with it), then feel free to pick up this PR and resolve the design questions:

There are a bunch of possibilities, like .sort_by_key(|x| x.total_order_key()) (a method that returns impl Ord), .sort_by_key(Total) (a newtype wrapper like num::Wrapping), etc.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.