Personal tools

Type variables instead of concrete types

From HaskellWiki

Revision as of 13:27, 4 March 2008 by Lemming (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

If you are new to Haskell you may think that type variables and polymorphism are fancy things that are rarely used. Maybe you are surprised that type variables and type class constraints can increase safety and readability also if you are eventually using only one concrete type.

Imagine the Prelude would contain the following functions:

maximum :: [Integer] -> Integer
sum :: [Integer] -> Integer

Sure, the names are carefully chosen and thus you can guess what they do. But the signature is not as expressive as it could be. Indeed these functions are in the Prelude but with a more general signature.

maximum :: (Ord a) => [a] -> a
sum :: (Num a) => [a] -> a
These functions can also be used for
Integer
s,

but the signatures show which aspects of integers are actually required.

We realize that
maximum
is not about numbers, but can also be used for other ordered types, like
Char
. We can also conclude that
maximum []
is undefined, since the
Ord
class has no function to construct certain values and the input list does not contain an element of the required type.