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.
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 /=.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With