[Haskell-cafe] Eq Type Class: Overloading (==)

Cale Gibbard cgibbard at gmail.com
Sat Sep 17 01:13:52 EDT 2005


On 16/09/05, Tom Hawkins <tom at confluent.org> wrote:
> Hello,
> 
> Is it possible to overload (==) to a type other than a -> a -> Bool?
> 
> I have an abstract datatype that somewhat behaves like a C integer: a
> comparison returns a boolean represented as the same datatype:
> 
> (==) :: my_type -> my_type -> my_type
> 
> Thanks for any help!
> 
> -Tom

You largely wouldn't want to -- the thing that makes the usual type
for (==) useful is that lots of functions make use of the Bool result
with if/then/else. If you change the Eq typeclass, then a large chunk
of the standard library is going to break, and it won't be all that
easy to correct, because if-then-else-expressions all expect a Bool.
You'd want to add a typeclass for boolean-interpretable values, and
fix up ghc to use it with if-expressions.

Haskell doesn't use ad-hoc polymorphism, so you're out of luck if you
want to keep the usual equality test around and have it overlap with
your function of another type. Further, there wouldn't be much point
to that kind of polymorphism, since functions requiring (==) to give a
Boolean result would simply break, and that would be nearly all of
them.

You can of course give the new kind of comparison another name though.
(===) isn't taken, for instance. You can even develop a similar
typeclass around it if you like. (Look how Eq is written in the
prelude.)

It may also be useful to have a function around which projects one of
your values down to a Bool. If you want to do that generically, you
may also want a class method which does that.

Here's an example of the sort of class you might want.

class Equative t where
   (===) :: t -> t -> t
   isTrue :: t -> Bool
   isFalse :: t -> Bool
   -- Minimal complete definition: (===) and one of isTrue or isFalse.
   isFalse = not . isTrue
   isTrue = not . isFalse

hope this helps,
 - Cale


More information about the Haskell-Cafe mailing list