Higher-ranked Polymorphism
   HOME

TheInfoList



OR:

In
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s and
type theory In mathematics and theoretical computer science, a type theory is the formal presentation of a specific type system. Type theory is the academic study of type systems. Some type theories serve as alternatives to set theory as a foundation of ...
, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorphic
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
s and
data type In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these ...
s are sometimes called generic functions and generic datatypes, respectively, and they form the basis of
generic programming Generic programming is a style of computer programming in which algorithms are written in terms of data types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneer ...
. Parametric polymorphism may be contrasted with
ad hoc polymorphism In programming languages, ad hoc polymorphismC. StracheyFundamental concepts in programming languages Lecture notes for International Summer School in Computer Programming, Copenhagen, August 1967 is a kind of polymorphism in which polymorphic fu ...
. Parametrically polymorphic definitions are ''uniform'': they behave identically regardless of the type they are instantiated at. In contrast, ad hoc polymorphic definitions are given a distinct definition for each type. Thus, ad hoc polymorphism can generally only support a limited number of such distinct types, since a separate implementation has to be provided for each type.


Basic definition

It is possible to write functions that do not depend on the types of their arguments. For example, the
identity function Graph of the identity function on the real numbers In mathematics, an identity function, also called an identity relation, identity map or identity transformation, is a function that always returns the value that was used as its argument, unc ...
\mathsf(x) = x simply returns its argument unmodified. This naturally gives rise to a family of potential types, such as \mathsf \to \mathsf, \mathsf \to \mathsf, \mathsf \to \mathsf, and so on. Parametric polymorphism allows \mathsf to be given a single, most general type by introducing a
universally quantified In mathematical logic, a universal quantification is a type of quantifier, a logical constant which is interpreted as "given any", "for all", "for every", or "given an arbitrary element". It expresses that a predicate can be satisfied by ev ...
type variable In type theory and programming languages, a type variable is a mathematical variable ranging over types. Even in programming languages that allow mutable variables, a type variable remains an abstraction, in the sense that it does not correspond ...
: :\mathsf : \forall \alpha. \alpha \to \alpha The polymorphic definition can then be ''instantiated'' by substituting any concrete type for \alpha, yielding the full family of potential types. The identity function is a particularly extreme example, but many other functions also benefit from parametric polymorphism. For example, an \mathsf function that
concatenate In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalizations of concatenati ...
s two
lists A list is a set of discrete items of information collected and set forth in some format for utility, entertainment, or other purposes. A list may be memorialized in any number of ways, including existing only in the mind of the list-maker, but ...
does not inspect the elements of the list, only the list structure itself. Therefore, \mathsf can be given a similar family of types, such as \mathsf\times mathsf\to mathsf/math>, \mathsf\times mathsf\to mathsf/math>, and so on, where /math> denotes a list of elements of type T. The most general type is therefore :\mathsf : \forall \alpha.
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
\times
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
\to
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
/math> which can be instantiated to any type in the family. Parametrically polymorphic functions like \mathsf and \mathsf are said to be ''parameterized over'' an arbitrary type \alpha. Both \mathsf and \mathsf are parameterized over a single type, but functions may be parameterized over arbitrarily many types. For example, the \mathsf and \mathsf functions that return the first and second elements of a
pair Pair or PAIR or Pairing may refer to: Government and politics * Pair (parliamentary convention), matching of members unable to attend, so as not to change the voting margin * ''Pair'', a member of the Prussian House of Lords * ''Pair'', the Fren ...
, respectively, can be given the following types: : \begin \mathsf & : \forall \alpha. \forall \beta. \alpha \times \beta \to \alpha \\ \mathsf & : \forall \alpha. \forall \beta. \alpha \times \beta \to \beta \end In the expression \mathsf((3, \mathsf)), \alpha is instantiated to \mathsf and \beta is instantiated to \mathsf in the call to \mathsf, so the type of the overall expression is \mathsf. The
syntax In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
used to introduce parametric polymorphism varies significantly between programming languages. For example, in some programming languages, such as
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
, the \forall \alpha quantifier is implicit and may be omitted. Other languages require types to be instantiated explicitly at some or all of a parametrically polymorphic function's
call site In programming, a call site of a function or subroutine is the location (line of code) where the function is called (or may be called, through dynamic dispatch). A call site is where zero or more arguments are passed to the function, and zero or m ...
s.


History

Parametric polymorphism was first introduced to programming languages in ML in 1975. Today it exists in
Standard ML Standard ML (SML) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Modular programming, modular, Functional programming, functional programming language with compile-time type checking and t ...
,
OCaml OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
, F#,
Ada Ada may refer to: Arts and entertainment * '' Ada or Ardor: A Family Chronicle'', a novel by Vladimir Nabokov Film and television * Ada, a character in 1991 movie '' Armour of God II: Operation Condor'' * '' Ada... A Way of Life'', a 2008 Bollywo ...
,
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
, Mercury,
Visual Prolog Visual Prolog, previously known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. It was marketed by Borland as Turbo Prolog (version 1.0 in 1986 and version 2.0 in 1988). It is now developed and marketed by ...
, Scala,
Julia Julia may refer to: People *Julia (given name), including a list of people with the name *Julia (surname), including a list of people with the name *Julia gens, a patrician family of Ancient Rome *Julia (clairvoyant) (fl. 1689), lady's maid of Qu ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
,
TypeScript TypeScript (abbreviated as TS) is a high-level programming language that adds static typing with optional type annotations to JavaScript. It is designed for developing large applications and transpiles to JavaScript. It is developed by Micr ...
, C++ and others.
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, C#,
Visual Basic .NET Visual Basic (VB), originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language developed by Microsoft and implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the ...
and
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
have each introduced "generics" for parametric polymorphism. Some implementations of type polymorphism are superficially similar to parametric polymorphism while also introducing ad hoc aspects. One example is C++
template specialization Generic programming is a style of computer programming in which algorithms are written in terms of data types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneer ...
.


Predicativity, impredicativity, and higher-rank polymorphism


Rank-1 (predicative) polymorphism

In a '' predicative'' type system (also known as a '' prenex polymorphic'' system), type variables may not be instantiated with polymorphic types. Predicative type theories include
Martin-Löf type theory Intuitionistic type theory (also known as constructive type theory, or Martin-Löf type theory (MLTT)) is a type theory and an alternative foundation of mathematics. Intuitionistic type theory was created by Per Martin-Löf, a Swedish mathematicia ...
and Nuprl. This is very similar to what is called "ML-style" or "Let-polymorphism" (technically ML's Let-polymorphism has a few other syntactic restrictions). This restriction makes the distinction between polymorphic and non-polymorphic types very important; thus in predicative systems polymorphic types are sometimes referred to as ''type schemas'' to distinguish them from ordinary (monomorphic) types, which are sometimes called ''monotypes''. A consequence of predicativity is that all types can be written in a form that places all quantifiers at the outermost (prenex) position. For example, consider the \mathsf function described above, which has the following type: :\mathsf : \forall \alpha.
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
\times
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
\to
alpha Alpha (uppercase , lowercase ) is the first letter of the Greek alphabet. In the system of Greek numerals, it has a value of one. Alpha is derived from the Phoenician letter ''aleph'' , whose name comes from the West Semitic word for ' ...
/math> In order to apply this function to a pair of lists, a concrete type T must be substituted for the variable \alpha such that the resulting function type is consistent with the types of the arguments. In an ''impredicative'' system, T may be any type whatsoever, including a type that is itself polymorphic; thus \mathsf can be applied to pairs of lists with elements of any type—even to lists of polymorphic functions such as \mathsf itself. Polymorphism in the language ML is predicative. This is because predicativity, together with other restrictions, makes the
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
simple enough that full
type inference Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
is always possible. As a practical example,
OCaml OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
(a descendant or dialect of ML) performs type inference and supports impredicative polymorphism, but in some cases when impredicative polymorphism is used, the system's type inference is incomplete unless some explicit type annotations are provided by the programmer.


Higher-rank polymorphism

Some type systems support an impredicative function type constructor even though other type constructors remain predicative. For example, the type (\forall \alpha. \alpha \rightarrow \alpha) \rightarrow T is permitted in a system that supports higher-rank polymorphism, even though forall \alpha. \alpha \rightarrow \alpha/math> may not be. A type is said to be of rank ''k'' (for some fixed integer ''k'') if no path from its root to a \forall quantifier passes to the left of ''k'' or more arrows, when the type is drawn as a tree. A type system is said to support rank-''k'' polymorphism if it admits types with rank less than or equal to ''k''. For example, a type system that supports rank-2 polymorphism would allow (\forall \alpha. \alpha \rightarrow \alpha) \rightarrow T but not ((\forall \alpha. \alpha \rightarrow \alpha) \rightarrow T) \rightarrow T. A type system that admits types of arbitrary rank is said to be "rank-''n'' polymorphic".
Type inference Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
for rank-2 polymorphism is decidable, but for rank-3 and above, it is not.


Impredicative polymorphism

''Impredicative polymorphism'' (also called ''first-class polymorphism'') is the most powerful form of parametric polymorphism. In
formal logic Logic is the study of correct reasoning. It includes both formal and informal logic. Formal logic is the study of deductively valid inferences or logical truths. It examines how conclusions follow from premises based on the structure o ...
, a definition is said to be impredicative if it is self-referential; in type theory, it refers to the ability for a type to be in the domain of a quantifier it contains. This allows the instantiation of any type variable with any type, including polymorphic types. An example of a system supporting full impredicativity is
System F System F (also polymorphic lambda calculus or second-order lambda calculus) is a typed lambda calculus that introduces, to simply typed lambda calculus, a mechanism of universal quantification over types. System F formalizes parametric polymorph ...
, which allows instantiating \forall \alpha. \alpha \to \alpha at any type, including itself. In
type theory In mathematics and theoretical computer science, a type theory is the formal presentation of a specific type system. Type theory is the academic study of type systems. Some type theories serve as alternatives to set theory as a foundation of ...
, the most frequently studied impredicative typed λ-calculi are based on those of the
lambda cube In mathematical logic and type theory, the λ-cube (also written lambda cube) is a framework introduced by Henk Barendregt to investigate the different dimensions in which the calculus of constructions is a generalization of the simply typed λ-c ...
, especially System F.


Bounded parametric polymorphism

In 1985,
Luca Cardelli Luca Andrea Cardelli is an Italian computer scientist who is a research professor at the University of Oxford, UK. Cardelli is well known for his research in type theory and operational semantics. Among other contributions, in programming lang ...
and
Peter Wegner Peter Wegner may refer to: * Peter Wegner (computer scientist) (1932–2017), professor of computer science at Brown University, Rhode Island, United States * Peter Wegner (American artist) (born 1963) * Peter Wegner (Australian artist) See also

recognized 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 whether an item is included in a list, we need to compare the items for equality. In
Standard ML Standard ML (SML) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Modular programming, modular, Functional programming, functional programming language with compile-time type checking and t ...
, 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 Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
, bounding is achieved by requiring types to belong to a
type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T a ...
; thus the same function has the type \mathrm \, \alpha \, \Rightarrow \alpha \, \rightarrow \left alpha \right\rightarrow \mathrm in Haskell. In most object-oriented programming languages that support parametric polymorphism, parameters can be constrained to be subtypes of a given type (see the articles
Subtype polymorphism In programming language theory, subtyping (also called subtype polymorphism or inclusion polymorphism) is a form of type polymorphism. A ''subtype'' is a datatype that is related to another datatype (the ''supertype'') by some notion of substitu ...
and
Generic programming Generic programming is a style of computer programming in which algorithms are written in terms of data types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneer ...
).


See also

*
Parametricity In programming language theory, parametricity is an abstract uniformity property enjoyed by parametrically polymorphic functions, which captures the intuition that all instances of a polymorphic function act the same way. Idea Consider this ex ...
*
Polymorphic recursion In computer science, polymorphic recursion (also referred to as Robin Milner, Milner–Alan Mycroft, Mycroft typability or the Milner–Mycroft calculus) refers to a recursion (computer science), recursive parametric polymorphism, parametric ...
* Type class#Higher-kinded polymorphism *
Trait (computer programming) In computer programming, a trait is a language concept that represents a set of methods that can be used to extend the functionality of a class. Rationale In object-oriented programming, behavior is sometimes shared between classes which are n ...


Notes


References

* * . * * . * . * * * {{Data types Generic programming Polymorphism (computer science) Type theory