3
$\begingroup$

I'm reading up on type classes, and started looking at the paper Type Classes in Haskell.

In Section 2.2 - Superclasses, the authors use the following example:

class (Eq a) => Ord a where 
   (<)  :: a -> a -> Bool
   (<=) :: a -> a -> Bool

Then, they proceed to state that "This declares that type a belongs to class Ord if there are operations (<) and (<=) of the appropriate type and if a belongs to class Eq. Thus, if (<) is defined on some type, then (==) must be defined on that type as well."

The second sentence does not make any sense to me; why would a type that defines (<) have to define (==) if it is not declared to be an instance of either Ord or Eq?

$\endgroup$
4
$\begingroup$

Simple answer: When the above class definition is in scope, you simply cannot bind (<) or (<=) except as part of an instance declaration for Ord.

$\endgroup$
  • $\begingroup$ Thank you. I see that my lacking experience with Haskell is confusing me. Could you please clarify exactly what it means for a type class to be in scope? $\endgroup$ – Eyvind Mar 6 '12 at 12:44
  • 1
    $\begingroup$ A class is in scope when it is defined in the current module (Haskell only allows classes to be defined on the module level). A class or its methods can also be imported from another module, and somewhat more complicated rules apply if the import is not unqualified, or omits some methods. Not sure I remember the exact details there, since that part of Haskell is rather ad-hoc. $\endgroup$ – Andreas Rossberg Mar 6 '12 at 14:02
4
$\begingroup$

[This is the same answer as Andreas Rossberg's, a bit more elaborated.]

Note that the only way you can overload a function symbol in Haskell is via type classes. So, if I want to define < for some type, say (Int, Int), then the only way to do so is by saying that (Int, Int) is an instance of Ord. But, in order to do that, (Int, Int) must first be an instance of Eq. So, I have to make (Int, Int) an instance of Eq, define its == operation, then make it an instance of Ord and define its < and <= operations.

[You might also see the related question Type classes vs object interfaces where similar issues are mentioned.]

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.