Using parametric polymorphism, a function or a data type can be written generically so that it can deal equally well with any objects without depending on their type. For example, a function append that joins two lists can be constructed so that it does not care about the type of elements: it can append lists of integers, lists of real numbers, lists of strings, and so on. Let the type variable a denote the type of elements in the lists. Then append can be typed [a] Ã [a] â [a], where [a] denotes a list of elements of type a. We say that the type of append is parameterized by a for all values of a. (Note that since there is only one type variable, the function cannot be applied to just any pair of lists: the pair, as well as the result list, must consist of the same type of elements.) For each place where append is applied, a value is decided for a.
Parametric polymorphism was first introduced to programming languages in ML in 1976. Today it exists in Standard ML, O'Caml, Haskell, and others. Some argue that templates should be considered an example of parametric polymorphism, though instead of actually producing generic code, the implementations generate specific code for each type value of a that a function is used with.
Parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. It is thus irrelevant in dynamically typed languages, since by definition they lack static type-safety. However, any dynamically typed function f that takes n arguments can be given a static type using parametric polymorphism: f : p1 Ã ... Ã pn â r, where p1, ..., pn and r are type parameters. Of course, this type is completely insubstantial and thus essentially useless. Instead, the types of arguments and return value are observed in run-time to match the operations performed on them.
Cardelli and Wegner recognized in 1985 the advantages of allowing bounds on the type parameters. Many operations require some knowledge of the data types but can otherwise work parametrically. For example, to check if an item is included in a list, we need to compare the items for equality. In Standard ML, type parameters of the form ’’a are restricted so that the equality operation is available, thus the function would have the type ’’a à ’’a list â bool and ’’a can only be a type with defined equality. In Haskell, bounding is achieved by requiring types to belong to a type class; thus the same function has the type Eq a â a â [a] â Bool in Haskell. In most object-oriented programming languages that support parametric polymorphism, parameters can be constrained to be subtypes of a given type