Skip to content

deriving Ord can produce incorrect and inefficient instances

This bug was spotted by Barak Pearlmutter in http://www.haskell.org/pipermail/haskell-cafe/2010-April/076762.html.

data T = T Double deriving( Eq, Ord )

*Main> T (0/0) > T (0/0)
True
*Main> (0/0) > (0/0)
False

This happens because the derived Ord instance only defines compare and relies on default method definitions for everything else. Comparisons involving !NaNs always return False, however, compare (arbitrarily) returns GT in this case.

Irrespective of this particular wart, this is what GHC ultimately produces for (<=):

T.$fOrdT_$c<= =
  \ (x_ahF :: T.T) (y_ahG :: T.T) ->
    case x_ahF of _ { T.T a1_afL ->
    case y_ahG of _ { T.T b1_afM ->
    case a1_afL of _ { GHC.Types.I# x#_ah1 ->
    case b1_afM of _ { GHC.Types.I# y#_ah5 ->
    case GHC.Prim.<# x#_ah1 y#_ah5 of _ {
      GHC.Bool.False -> GHC.Prim.==# x#_ah1 y#_ah5;
      GHC.Bool.True -> GHC.Bool.True
    }
    }
    }
    }
    }

Note that the definition uses two comparisons even though (<=) for Double uses just one: (<=##). In general, relying on default method definitions when deriving Ord can be inefficient because the individual comparison operators might very well be faster than compare for the wrapped types.

Trac metadata
Trac field Value
Version 6.13
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information