Haskell Type Classes: Constrained Parametric Polymorphism
Haskell's type class system is a powerful mechanism to support systematic polymorphism.
The Num Class
For example, Haskell's Num class is the class of
all numeric types. It allows polymorphic functions
such as (+) to be defined for all numeric types.
(+) :: (Num a) => a -> a -> a
Here (Num a) => is a type context, stating that a is an instance of type clase Num, i.e., a numeric type.
Three important instances of type class Num are
Int- fixed precision integers based on machine register size (typically 32-bit or 64-bit).Integer- arbitrary precision integers.Float- single-precision floating point numbers.
Numeric literals such as 17 and 5.21 are also polymorphic.
Prelude> :type 17 17 :: Num a => a Prelude> :type 5.21 5.21 :: Fractional a => a
Fractional is a subclass of Num that excludes Int and Integer. Depending on context, type inference narrows types to ones which support given operations.
Prelude> :type 17 + 5.21 17 + 5.21 :: Fractional a => a Prelude> 17 + 5.21 22.21
In the example, 17 is first narrowed from Num to Fractional to match the polymorphic Fractional type.
Updated Mon Oct. 12 2015, 20:13 by cameron.