When we introduced lists, we mentioned that the list type is polymorphic. We’ll talk about Haskell’s polymorphism in more detail here.
If we want to fetch the last element of a
list, we use the
The value that it returns must have the same type as the elements of the
last operates in the same
way no matter what type those elements actually are:
To capture this idea, its type signature contains a type variable:
:type lastlast :: [a] -> a
the type variable. We can read the signature as “takes a list, all of
whose elements have some type a, and returns a value of the same type
Type variables always start with a lowercase letter. You can always tell a type variable from a normal variable by context, because the languages of types and functions are separate: type variables live in type signatures, and regular variables live in normal expressions.
It’s common Haskell practice to keep the names of type variables very short. One letter is overwhelmingly common; longer names show up infrequently. Type signatures are usually brief; we gain more in readability by keeping names short than we would by making them descriptive.
When a function has type variables in its signature, indicating that some of its arguments can be of any type, we call the function polymorphic.
When we want to apply
last to, say, a list of Char,
the compiler substitutes Char for each ...