I understand why the floats don't have an implementation for Ord
but that doesn't particularly help me when I want to be lazy and use iterators.
Is there a workaround or an easy way to take the minimum / min / min_by of an iterator containing floating point numbers?
I know one can sort (which is slow) or wrap it in another type and implement the needed trades (which is verbose) but I am hoping for something a little more elegant.
If you know your data does not contain NaNs, then assert that fact by unwrapping the comparison:
If your data may have NaNs, you need to handle that case specifically. One solution is to say that all 16,777,214 NaN values are equal to each other and are always greater than or less than other numbers:
There are numerous crates available that can be used to give you whichever semantics your code needs.
You should not use
partial_cmp(b).unwrap_or(Ordering::Equal)
because it provides unstable results when NaNs are present, but it leads the reader into thinking that they are handled:Floats have their own
min
andmax
methods that handle NaN consistently, so you can fold over the iterator:Prints
-10
.If you want different NaN handling, you can use
PartialOrd::partial_cmp
. For example, if you wish to propagate NaNs, fold with:Perhaps like this?
One thing I struggled with is that
sort_by
mutates the vector in place so you can't use it in a chain directly.