I was reading the definition for the Eq
typeclass in the Data library, and I'm confused. At what point is it realized that two values are equal or not equal. From what I see, it looks like they would just call each other ad infinitum.
It's defined as so:
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
Would somebody mind explaining where it realizes the Bool
value? Are they even calling each other, or is something else going on?
That’s the default implementation of those methods, and yes, it is circular. If you use them as-is, you’ll loop:
data Foo = Foo
instance Eq Foo
> Foo == Foo
^CInterrupted
The circular definitions exist so you can implement (==)
and get (/=)
for free, or vice versa:
data Foo = Foo
instance Eq Foo where
x == y = True
> Foo /= Foo
False
See also the Ord class, which explains what the minimal complete definition is in that particular case.
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