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

StackOverflow https://stackoverflow.com/questions/17318320

문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top