Reputation: 123
I am new to Haskell and i come from c++ background.
I am having some trouble understanding the relation between types and type classes.
From what i understand type classes specify a bunch of functions. Like the Eq
type class specifies ==
and /=
.
But now suppose i have a type t
, What does it mean when i say that t
is an instance of Eq
type class. Does it simply mean that t
supports and implements the functions specified by Eq
?
Upvotes: 2
Views: 78
Reputation: 116139
Does it simply mean that t supports and implements the functions specified by Eq ?
Yes, precisely.
It simply means that there's an instance of Eq t
which defines the operator (==)
, as required by Eq
. You can therefore use said operator on type t
in your code.
A silly example:
data MyPair = P Int String
instance Eq MyPair where
(P i1 s1) == (P i2 s2) = -- we define equality ...
i1==i2 && s1==S2 -- ... as component-wise equality
testTrue :: Bool
testTrue = (P (1+1) "aa") == (P 2 ("a"++"a"))
In the example above, the common idiom would actually be
data MyPair = P Int String deriving Eq
which automatically derives the instance -- so there's no need to write it explicitly.
Upvotes: 6