A type class defines a generic interface abstracting some common feature over a variety of types. For example, many numeric structures, such as integer, vectors and matrices, allow the addition of elements in the structure. We capture the property of “being addable” as follows:
The variable a is a type parameter. The identifier “+” is chosen because we are generalizing addition, but it is not the usual addition of integers. Any symbols would acceptable:
To say that some structure is addable we use an instance declaration. For example, the following declaration states that the integers are addable and the addition operation is the addition function defined in the Prelude.
Next, we represent vectors (without an explicit data declaration) as lists of addables and we define the addition of vectors as the component-wise addition of their elements:
The symbol “+” refers to the same symbol defined in the Addable type class and it is applied to the vectors’ elements. With these definition we can add two vectors as follows: