Type Classes
Like most other programming languages, Haskell features a number of overloaded operators and functions, such as (+)
, that work at different types. For instance, (+)
has the following four types:
(+) :: Int -> Int -> Int (+) :: Integer -> Integer -> Integer (+) :: Float -> Float -> Float (+) :: Double -> Double -> Double
Overloading is not the same as (parametric) polymorphism: (+)
does not have the type a -> a -> a
and does not work on all possible types. Overloading means that the operator only works for a specific set of types and that the operator’s behavior is different for each type.
In many languages, overloading is ad hoc: it exists for a fixed number of operators and functions and a fixed set of types. Moreover, a function that uses an overloaded operator often has to be written once for each type. For example, see the following:
plusInt :: Int -> Int -> Int plusInt x y = x + y plusFloat :: Float -> Float...