210: Type Variables (Haskell)
June 9, 2018
Posted by on
In Haskell, type variables are roughly the equivalent of generics in languages like Java. They enable a function to operate on and return different types, so long as the function doesn’t depend on any specific behavior of the types involved. (These are called polymorphic functions.)
For instance, if in GHCI we use
:t head to examine the type of the
head function which returns the first element of a list, we see it has the type
head :: [a] -> a.
a is a type variable, meaning it could be any type. This just means
head takes a list with elements of any type
a and returns a single element of that same type.
As another example,
:t fst gives
fst :: (a, b) -> a. Since pairs in Haskell aren’t homogenous, it’s possible that a pair’s first and second elements have different types
b respectively (although they could be the same).
fst just returns a single element of type