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

I read a book and it talks about defining typeclass Eq

In Eq, there are two functions == , /= , 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 an element of another function.

I don’t understand that I don’t see the basic argument in mutual recursion, and I don’t understand why the functions will stop and return the result.

+4
source share
1 answer

Mutual recursion will not stop with these definitions - it will return endlessly. The idea is that you redefine one of the two definitions using your own base code when implementing the Eq .

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

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

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

The reason Eq provides the default implementation for == and /= is because you can decide whether you want to provide a definition for == or /= and you will get another for free even if you choose /= .

+7
source

Source: https://habr.com/ru/post/1488264/


All Articles