Matt
Matt

Reputation: 515

Haskell Eq definition realizing a result

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?

Upvotes: 6

Views: 180

Answers (1)

Josh Lee
Josh Lee

Reputation: 177550

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.

Upvotes: 11

Related Questions