3 Main Features of Curry

3.10 Type classes

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:

class Addable a where
  (+) :: a ->  a  -> a

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.

instance Addable Int where
  x + y = x Prelude.+ y

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:

instance Addable a => Addable [a] where
  xs + ys = zipWith (+) xs ys

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:

testv :: [Int]
testv = [1,2,3] + [4,5,6]
Exercise 5

Define a matrix as follows:
WWW data Matrix a = Matrix [[a]]
and make it addable using an instance declaration. [Browse Program][Download Program]