Theory
Parametric polymorphism lets one data description work for any element type.
data List a = Nil | Cons a (List a)List is a type constructor; a is a type parameter.
Benefits
- Code reuse โ functions like
map,lengthwork for everya. - Type safety โ operations preserve element type.
Example
data Tree a
= Empty
| Node a (Tree a) (Tree a)
singleton :: a -> Tree a
singleton x = Node x Empty EmptyGeneration and pattern-matching mirror concrete types:
count :: Tree a -> Int
count Empty = 0
count (Node _ l r) = 1 + count l + count r