[Haskell-cafe] FW: Why does this Ord-class instance crash?

Miguel Mitrofanov miguelimo38 at yandex.ru
Fri May 21 13:35:17 EDT 2010


 From Prelude.hs:

class  (Eq a) => Ord a  where
     compare              :: a -> a -> Ordering
     (<), (<=), (>), (>=) :: a -> a -> Bool
     max, min             :: a -> a -> a

     compare x y = if x == y then EQ
                   -- NB: must be '<=' not '<' to validate the
                   -- above claim about the minimal things that
                   -- can be defined for an instance of Ord:
                   else if x <= y then LT
                   else GT

     x <  y = case compare x y of { LT -> True;  _ -> False }
     x <= y = case compare x y of { GT -> False; _ -> True }
     x >  y = case compare x y of { GT -> True;  _ -> False }
     x >= y = case compare x y of { LT -> False; _ -> True }

         -- These two default methods use '<=' rather than 'compare'
         -- because the latter is often more expensive
     max x y = if x <= y then y else x
     min x y = if x <= y then x else y

So, in your case:

Scalene > Failure
   ->  {Gee, there's no definition of ">" in this "Ord" instance; I'll  
have to take the default one}
compare Scalene Failure
   -> {There's no definition of "compare" either; again, the default  
one}
Scalene <= Failure
   -> {Again, there is no definition of "<="}
compare Scalene Failure
   -> loop



On 21 May 2010, at 21:06, R J wrote:

> Why does the following, trivial  code snippet below hang GHCi when I  
> type
> "Scalene > Failure", and what's the fix?
>
>
> data Triangle                  =  Failure
>                                |  Equilateral
>                                |  Isosceles
>                                |  Scalene
>                                deriving (Eq, Show)
>
> instance Ord Triangle where
>     Failure     < Failure      = False
>     Failure     < _            = True
>
>     Equilateral < Failure      = False
>     Equilateral < Equilateral  = False
>     Equilateral < _            = True
>
>     Isosceles   < Scalene      = True
>     Isosceles   < _            = False
>
>     Scalene     < _            = False
>
>
> (I tried submitting this to beginners at haskell.org, but even though  
> I've signed up for that mailing list, I got a bounce-back saying  
> that I needed admin approval to submit anything to that list, and I  
> haven't heard from an admin, so I'm posting it here.)
>
>
> The New Busy is not the too busy. Combine all your e-mail accounts  
> with Hotmail. Get busy._______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list