I am trying to figure out the purpose of type class, and what else is there if not using type class.
Is type class a way to define polymorphic functions?
Is type class the only way to define polymorphic functions? For example:
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
instance Eq Bool where
False == False = True
True == True = True
_ == _ = False
Can I define ==
and /=
for Bool
(and any other type) without using type class Eq
?
Where there is any other way, when shall I use which way to define polymorphic functions, by using type class or by using the other way?
You can always write unconstrained polymorphic function, that doesn't require any typeclass. A simple example is
length :: [a] -> Int
– this works without a typeclass, and (well, because) it works for any type a
whatsoever. Namely, length
doesn't actually care what the values in that list are, it only cares about the structure in which those values are contained. It never actually does anything with those values themselves, and the polymorphic type actually guarantees that.
If the polymorphic task you need is of this form, i.e. a type that you don't actually need to access, you just know it's there, then you should not write/invoke a type class, just use ML-style parametric polymorphism as in length
. However, quite often you will need to access the values themselves, inspect them in some way. Doing that without however limiting you to a particular concrete type is what type classes are there for. Eq
, as you quoted yourself, is an example.