Answers
- An ad hoc overloaded function (or operator) is similar to a polymorphic function in that it works for different types. Yet, it differs in two ways from a polymorphic function: 1) it does not work for all types, and 2) it has a different implementation per type. Haskell groups ad hoc overloaded functions into type classes, such as
Eq
with its(==)
and(/=)
methods. To indicate that a polymorphic function makes use of ad hoc overloaded operations, its type signature lists type class constraints on the type variables. For example,sort :: Ord a => [a] -> [a]
lists theOrd a
constraint to indicate that it works for all element types that provide total ordering. - You write a type class instance that provides implementations for the methods of the type class. Not all methods need to be implemented, only those that provide a minimal complete definition. For example, only
(==)
or(/=)
needs to be implemented forEq
. An instance is expected to satisfy the laws of the type...