4

I am reading the book, and it talks about the definition of typeclass Eq

There are two functions ==, /= in the Eq, and they are implemented as:

  x == y = not (x /= y)  
  x /= y = not (x == y)  

The book says that they are mutual recursion, the result of the function is in item of another function.

What I don't understand is that I don't see a base case in the mutual recursion, and I don't understand why the functions will stop and return a result.

code4j
  • 4,208
  • 5
  • 34
  • 51

1 Answers1

7

With those definitions, the mutual recursion won't stop - it will recurse infinitely. The idea is that you override one of the two definitions with your own base case when implementing the Eq typeclass.

So for example if you have a type data Foo = Bar | Baz your Eq instance could look like this:

instance Eq Foo where
  Bar == Bar = True
  Baz == Baz = True
  _   == _   = False

Here we only defined ==, not /=, so /= will use its default definition not (x == y). However our definition of == will not call /= back, so its no longer mutually recursive and will terminate without problems.

The reason that Eq provides default implementations for both == and /= is so that you can decide whether you want to provide a definition for == or /= and you get the other one for free even if you choose /=.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 4
    With [my proposal](http://hackage.haskell.org/trac/ghc/ticket/7633) -- hopefully to be in the next version of GHC -- you can specify the minimal complete definition of a class in a compiler-checkable way, so that you'd get a warning if you didn't implement either method. – shachaf Jun 26 '13 at 11:12
  • @sepp2k thanks for your explanation. In fact, there is an explanation in the book just below but I could not realize it exists... – code4j Jun 26 '13 at 11:22