Inconsistent behavior of Seq.sort and Seq.sortBy for a sequence of floats containing NaN

When sorting a sequence of floats containing NaN, Seq.sort puts NaNs at the head of the result:

> [ 0.0; nan; 1.0; nan; -1.0 ] |> Seq.sort val it : seq<float> = seq [nan; nan; -1.0; 0.0; ...] 

However, Seq.sortBy seems to fail and just passes the sequence unsorted. Presumably, this is due to the fact that NaN violates the basic principles of ordering.

 > [ 0.0; nan; 1.0; nan; -1.0 ] |> Seq.sortBy id val it : seq<float> = seq [0.0; nan; 1.0; nan; ...] 

An exception is not thrown, which may indicate that sortBy was unable to create a sorted list, and this may lead to unexpected behavior in the code that relies on it. It's easy to code the problem as soon as you find it, but it's harder to anticipate and probably cause errors.

Is there any good reason for sorting and sortBy to be inconsistent this way?

+6
source share
1 answer

Source: https://habr.com/ru/post/986315/


All Articles