Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do the implementation of Eq typeclass function: x == y = not (x /= y) x /= y = not (x == y) work?

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.

like image 443
code4j Avatar asked Mar 23 '23 09:03

code4j


1 Answers

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 /=.

like image 141
sepp2k Avatar answered Apr 26 '23 09:04

sepp2k