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 IntListSimilarly, the type of lists of Booleans can be defined as
data BoolList = Nil | Cons Bool BoolListTo make this more generic, we can use a type variable instead of the concrete type (
IntorBoolhere).
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” (whereais a type variable) can be defined analogously to the two types above, asdata List a = Nil | Cons a (List a)This type is equivalent to the native Haskell type
[a].