DEV Community

lotz
lotz

Posted on

Notes on sorting [Double]

If NaN is included in the list, it's not sorted as expected.

> import Data.List
> let nan = 0/0 :: Double
> sort [3,2,nan,1,5,nan,4]
[1.0,4.0,NaN,5.0,NaN,2.0,3.0]

This behavior seems to be due to the strange behavior when comparing nan to itself or to a number.

> nan < nan
False
> nan == nan
False
> nan > nan
False
> compare nan nan
GT
> nan < 0
False
> nan == 0
False
> nan > 0
False
> compare nan 0
GT

Wat a horror.

When sorting a list that is likely to contain NaN, it is better to use isNaN

isNaN :: RealFloat a => a -> Bool

to remove the NaN or to sort it after proper processing.

> sort . filter (not . isNaN) $ [3,2,nan,1,5,nan,4]
[1.0,2.0,3.0,4.0,5.0]

> sort . map (\x -> if isNaN x then -1 else x) $ [3,2,nan,1,5,nan,4]
[-1.0,-1.0,1.0,2.0,3.0,4.0,5.0]

Top comments (0)