Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

f#

When sorting a sequence of floats containing a NaN, Seq.sort puts the 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 appears to fail, and simply passes the sequence on, unsorted. Presumably this is because NaN violates basic ordering principles.

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

No exception is thrown which might indicate that sortBy failed to produce a sorted list, and this can lead to surprising behaviour in code that relies on it. It's easy to code around the problem once you find it, but harder to anticipate, and so likely to cause bugs.

Is there a good reason for sort and sortBy being inconsistent in this way?

like image 263
ben Avatar asked Apr 30 '15 16:04

ben


1 Answers

This issue is fixed upstream: https://github.com/Microsoft/visualfsharp/issues/370

like image 144
Daniel Fabian Avatar answered Nov 02 '22 04:11

Daniel Fabian