Carter Weinberg
Carter Weinberg

Reputation: 95

Basic Implementation of Equals in Haskell

I have something like

data Example =
    Ex Integer

How would I go about implementing equals for this?

Furthest I have gotten is

instance Eq Example where 
    (Ex _) == (Ex _) = True 

But that is wrong because that always evaluates to true. I could put concrete instances of an integer instead of the '_' character, but then I would have to do that for every integer.

Thanks for your time everyone!

Upvotes: 1

Views: 134

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

but then I would have to do that for every integer.

No, since Integer is a member of the Eq typeclass. We can thus make use of (==) implemented for Integer, and thus "unpack" the Ex data constructor, and check the equality of the parameters:

instance Eq Example where 
    Ex x == Ex y = x == y

That being said, you can let Haskell implement the Eq instance itself with:

data Example = Ex Integer deriving Eq

The automatic implementation of Eq specifies that two items are the same if they have the same data constructor, and the parameters are equal (with the (==) function).

Upvotes: 6

Related Questions