Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit Eq class in Haskell?

Tags:

haskell

I want to define new class PersonOP which inherit Eq class. I mean I have a data type

data Person a = {name:a,age:Int}

i want to create a class like

   class (Eq a)=> PersonOp a where

and then make instance like this

   instance PersonOp (Person a) where

         (Person a)==(Person a) = equality (Person a) (Person a)

when i implement something like in class

     (==)::a->a->Bool 
     x==y = not (x/=y) 

i got error how can i fix it?

like image 902
Alihuseyn Avatar asked Dec 03 '25 16:12

Alihuseyn


1 Answers

It would be simplest to derive equality for your person class:

data Person a = Person {name::a, age::Int}
   deriving Eq

so that you can do

*Main> Person "James" 53 == Person "Fred" 23
False
*Main> Person "James" 53 == Person "James" 53
True

This automatically creates an == function for Person a based on the == for a.

Why

In haskell, == is a member of the Eq class. You can only define == by creating an instance of the Eq class, and if you try to define it otherwise, you will get an error.

Making it a part of a class makes it easy for you to define equality as appropriate for your data types.

Defining an instance by hand

Instead of deriving Eq, you can define it yourself, so for example:

data Person a = Person {name::a, age::Int}

instance Eq a => Eq (Person a) where
   someone == another = name someone == name another
                      && age someone == age another
like image 77
AndrewC Avatar answered Dec 06 '25 10:12

AndrewC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!