Reputation: 158
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?
Upvotes: 3
Views: 524
Reputation: 158
I found answer
import Prelude hiding ((==))
data Person a = {name:a,age:Int}
class PersonOp a where
(==)::a->a->Bool
instance PersonOp (Person a) where
(Person a)==(Person a) = equality (Person a) (Person a)
Upvotes: -2
Reputation: 32455
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
.
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.
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
Upvotes: 13