Ad hoc polymorphism
We will start this chapter by exploring the concept of ad hoc polymorphism. We will learn that Haskell uses type classes to declare which operators and functions are overloaded, and uses type class constraints in function signatures to limit how type variables can be instantiated.
What is ad hoc polymorphism?
Haskell provides several operators that work on values of multiple types, such as the equality test (==
). We can, for instance, check whether two integer values are equal, two Boolean values, or two strings:
*Main> 1 == 2 False *Main> True == True True *Main> "hello" == "world" False
However, the operator does not work for all types. Notably, it does not work on functions. For example, we can’t compare the not :: Bool -> Bool
function to itself:
*Main> not == not <interactive>:2:1: error: • No instance for (Eq (Bool -> Bool)) arising from a use of '==&apos...