Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
Matt Avatar asked Jan 08 '13 22:01

Matt


1 Answers

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.

like image 198
Josh Lee Avatar answered Sep 25 '22 10:09

Josh Lee