Hacker News new | ask | show | jobs
by yorwba 3328 days ago
About floats implementing PartialOrd and not Ord:

I have not tried out Rust yet, but couldn't this be solved by wrapping the float in a single-field struct that checks for NaN on construction, implements Ord using PartialOrd and otherwise passes everything through to the ordinary float inside?

If this isn't possible, I'm definitely interested in the reasons.

1 comments

Every calculation will have to check for NaN, so it's a non-starter when you need a lot of float calculations.
The problem was in the context of looking up min_by_key with the key being a floating-point number, so I think the only NaN-check necessary should be for that key. I did not intend to imply that it should be done for all calculations, only those that need totally-ordered floats. (Or if you are really sure NaN will never happen, you leave out the check altogether, and claim total ordering anyway.)
I guess that is a particularly bad use case of specialization, which itself is proposed as an RFC [1] and approved for implementation. It would look pretty similar to, say, C++'s `vector<T>` and `vector<bool>` split, because it does something more than what it should do. Probably the better solution is to merge PartialOrd and Ord, as the benefit from having two traits has been always unclear (I personally have no strong opinion against or for that though).

[1] https://github.com/rust-lang/rfcs/blob/master/text/1210-impl...

If the type proved there could be no NaN, why would the check be needed?
0.0 is a finite number that yields NaN when divided by itself. The initial checking is not sufficient.
So check on construction, when doing operations with other unchecked floats, and when dividing. Any other operations that could produce a NaN?

Wait, are +-Inf considered unordered? Edit: Nope. inf == inf, so you should only have to worry about NaN. https://is.gd/Xi5jdr

If you want the full list: 0/0, ±inf/±inf, 0 x ±inf, ±inf x 0, inf + (-inf), (-inf) + inf, inf - inf, (-inf) - (-inf). This list is large enough to make NaN checking inefficient.
Thanks. Yeah maybe not.

It seems like the right way is to add min/max fns to the Iterator trait for PartialOrd that ignore items where partial_ord returns None.