Generic type

Generic type #

In Haskell #

Syntax #

We have already seen how to define a product type or a sum type.

Example. As we have seen earlier, the type of lists of integers can be defined as follows:

data IntList = Nil | Cons Int IntList

Similarly, the type of lists of Booleans can be defined as

data BoolList = Nil | Cons Bool BoolList

To make this more generic, we can use a type variable instead of the concrete type (Int or Bool here).

Syntax. A generic type in Haskell is declared as

data <typeName> <type variable 1> ... <type variable n> = <definition>

where <definition> is a type definition that may use the type variables declared on the left-hand side.

Example (continued). The parameterized type “list of a’s” (where a is a type variable) can be defined analogously to the two types above, as

data List a = Nil | Cons a (List a)

This type is equivalent to the native Haskell type [a].