#4019: deriving Ord can produce incorrect and inefficient instances
---------------------------------+------------------------------------------
    Reporter:  rl                |       Owner:                             
        Type:  bug               |      Status:  new                        
    Priority:  normal            |   Component:  Compiler                   
     Version:  6.13              |    Keywords:                             
          Os:  Unknown/Multiple  |    Testcase:                             
Architecture:  Unknown/Multiple  |     Failure:  Incorrect result at runtime
       Patch:  0                 |  
---------------------------------+------------------------------------------
 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.

-- 
Ticket URL: <http://hackage.haskell.org/trac/ghc/ticket/4019>
GHC <http://www.haskell.org/ghc/>
The Glasgow Haskell Compiler
_______________________________________________
Glasgow-haskell-bugs mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/glasgow-haskell-bugs

Reply via email to