Generic Types: Parametric Polymorphism
Haskell and other functional languages provide a system treatment of generic or parameterized types.
[a]
stands for the generic list type, that is, lists of a specific but unknown element typea
. Instances of this parametric type include[Char]]# and
Int.
(a, b)
stands for 2-tuples for some element typesa
andb
.
(a, a)
stands for 2-tuples of elements which both have the same typea
. Examples include(Int, Int)
and([Char], [Char])
but not(Int, Char)
.
a -> b -> Bool
stands for binary predicate functions that take arguments of possibly different typesa
andb
. Instances include:Char -> [Char] -> Bool
Int -> Int -> Bool
data Tree a = Empty | Binary a (Tree a) (Tree a)
is a parametric binary tree type.
Generic Functions
Many Haskell functions are generic, defined as functions having parameterized types.
For example, a function to take the last element of a list can be written as a polymorphic function applicable to any list type.
last :: [a] -> a last[x] = x last(x1:x2:xs) = last(x2:xs)
Polymorphic functions over binary trees also follow this pattern.
nodecount :: Tree a -> Int nodecount Empty = 0 nodecount (Binary x left right) = nodecount left + nodecount right + 1
List iteration with polymorphic functions
Haskell defines a very useful operation map
that applies a given function to all members of a list, return a list of the results.
This function has the following polymorphic type signature.
map :: (a -> b) -> [a] -> [b]
Examples:
sqr :: Int -> Int sqr x = x * x map sqr [1,2,3,4] = [1,4,9,16]
map
is built-in, but could be easily defined in Haskell.
map f [] = [] map f (x:xs) = (f x) : (map f xs)
Updated Mon Oct. 12 2015, 18:47 by cameron.