In
programming language theory
Programming language theory (PLT) is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of formal languages known as programming languages. Programming language theory is clos ...
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 ...
, polymorphism is the use of one symbol to represent multiple different types.
[: "Polymorphic types are types whose operations are applicable to values of more than one type."]
In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, polymorphism is the provision of one
interface to entities of different
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. The concept is borrowed from a principle in
biology
Biology is the scientific study of life and living organisms. It is a broad natural science that encompasses a wide range of fields and unifying principles that explain the structure, function, growth, History of life, origin, evolution, and ...
where an organism or species can have many different forms or stages.
The most commonly recognized major forms of polymorphism are:
* ''
Ad hoc polymorphism'': defines a common interface for an arbitrary set of individually specified types.
* ''
Parametric polymorphism
In programming languages and type theory, 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 polymorph ...
'': not specifying concrete types and instead use abstract symbols that can substitute for any type.
* ''
Subtyping
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 substi ...
'' (also called ''subtype polymorphism'' or ''inclusion polymorphism''): when a name denotes instances of many different classes related by some common superclass.
History
Interest in polymorphic
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 ...
s developed significantly in the 1990s, with practical implementations beginning to appear by the end of the decade. ''Ad hoc polymorphism'' and ''parametric polymorphism'' were originally described in
Christopher Strachey
Christopher S. Strachey (; 16 November 1916 – 18 May 1975) was a British computer scientist. He was one of the founders of denotational semantics, and a pioneer in programming language design and computer time-sharing.F. J. Corbató, et al., T ...
's ''
Fundamental Concepts in Programming Languages
''Fundamental Concepts in Programming Languages'' were an influential set of lecture notes written by Christopher Strachey for the International Summer School in Computer Programming at Copenhagen in August, 1967. It introduced much programming ...
'',
where they are listed as "the two main classes" of polymorphism. Ad hoc polymorphism was a feature of
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language member of the ALGOL family that was conceived as a successor to the ALGOL 60 language, designed with the goal of a much wider scope of application and ...
, while parametric polymorphism was the core feature of
ML's
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 ...
.
In a 1985 paper,
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 and
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 ...
introduced the term ''inclusion polymorphism'' to model subtypes and
inheritance
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
,
citing
Simula
Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of AL ...
as the first programming language to implement it.
Forms
Ad hoc polymorphism
Christopher Strachey
Christopher S. Strachey (; 16 November 1916 – 18 May 1975) was a British computer scientist. He was one of the founders of denotational semantics, and a pioneer in programming language design and computer time-sharing.F. J. Corbató, et al., T ...
chose the term ''ad hoc polymorphism'' to refer to polymorphic functions that can be applied to arguments of different types, but that behave differently depending on the type of the argument to which they are applied (also known as
function overloading
In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that f ...
or
operator overloading
In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading ...
).
[ The term "]ad hoc
''Ad hoc'' is a List of Latin phrases, Latin phrase meaning literally for this. In English language, English, it typically signifies a solution designed for a specific purpose, problem, or task rather than a Generalization, generalized solution ...
" in this context is not pejorative: instead, it means that this form of polymorphism is not a fundamental feature of the type system. In the 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 ...
example below, the add
functions seem to work generically over two types (integer
An integer is the number zero (0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number (−1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative in ...
and string
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
) when looking at the invocations, but are considered to be two entirely distinct functions by the compiler
In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
for all intents and purposes:
class AdHocPolymorphic
public class Adhoc
In dynamically typed
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). Usua ...
languages the situation can be more complex as the correct function that needs to be invoked might only be determinable at run time.
Implicit type conversion
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point val ...
has also been defined as a form of polymorphism, referred to as "coercion polymorphism".
Parametric polymorphism
''Parametric polymorphism'' allows a function or a data type to be written generically, so that it can handle values ''uniformly'' without depending on their type. Parametric polymorphism is a way to make a language more expressive while still maintaining full static type safety
In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that ...
.
The concept of parametric polymorphism applies to both 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 and functions. A function that can evaluate to or be applied to values of different types is known as a ''polymorphic function.'' A data type that can appear to be of a generalized type (e.g., a list
A list is a Set (mathematics), 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 t ...
with elements of arbitrary type) is designated ''polymorphic data type'' like the generalized type from which such specializations are made.
Parametric polymorphism is ubiquitous in functional programming, where it is often simply referred to as "polymorphism". The next example 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 ...
shows a parameterized list data type and two parametrically polymorphic functions on them:
data List a = Nil , Cons a (List a)
length :: List a -> Integer
length Nil = 0
length (Cons x xs) = 1 + length xs
map :: (a -> b) -> List a -> List b
map f Nil = Nil
map f (Cons x xs) = Cons (f x) (map f xs)
Parametric polymorphism is also available in several object-oriented languages. For instance, templates in C++ and D, or under the name generics in C#, 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 ...
, Java, and Go:
class List
List map(Func f, List xs)
John C. Reynolds
John Charles Reynolds (June 1, 1935 – April 28, 2013) was an American computer scientist.
Education and affiliations
John Reynolds studied at Purdue University and then earned a Doctor of Philosophy (Ph.D.) in theoretical physics from Harvard U ...
(and later Jean-Yves Girard
Jean-Yves Girard (; born 1947) is a French logician working in proof theory. He is a research director (emeritus) at the mathematical institute of University of Aix-Marseille, at Luminy.
Biography
Jean-Yves Girard is an alumnus of the Éc ...
) formally developed this notion of polymorphism as an extension to lambda calculus (called the polymorphic lambda calculus or 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 ...
). Any parametrically polymorphic function is necessarily restricted in what it can do, working on the shape of the data instead of its value, leading to the concept of parametricity.
Subtyping
Some languages employ the idea of ''subtyping'' (also called ''subtype polymorphism'' or ''inclusion polymorphism'') to restrict the range of types that can be used in a particular case of polymorphism. In these languages, subtyping allows a function to be written to take an object of a certain type ''T'', but also work correctly, if passed an object that belongs to a type ''S'' that is a subtype of ''T'' (according to the Liskov substitution principle). This type relation is sometimes written . Conversely, ''T'' is said to be a ''supertype'' of ''S'', written . Subtype polymorphism is usually resolved dynamically (see below).
In the following Java example cats and dogs are made subtypes of pets. The procedure letsHear()
accepts a pet, but will also work correctly if a subtype is passed to it:
abstract class Pet
class Cat extends Pet
class Dog extends Pet
static void letsHear(final Pet pet)
static void main(String[] args)
In another example, if ''Number'', ''Rational'', and ''Integer'' are types such that and (''Rational'' and ''Integer'' as subtypes of a type ''Number'' that is a supertype of them), a function written to take a ''Number'' will work equally well when passed an ''Integer'' or ''Rational'' as when passed a ''Number''. The actual type of the object can be hidden from clients into a black box
In science, computing, and engineering, a black box is a system which can be viewed in terms of its inputs and outputs (or transfer characteristics), without any knowledge of its internal workings. Its implementation is "opaque" (black). The te ...
, and accessed via object identity. If the ''Number'' type is ''abstract'', it may not even be possible to get your hands on an object whose ''most-derived'' type is ''Number'' (see abstract data type
In computer science, an abstract data type (ADT) is a mathematical model for data types, defined by its behavior (semantics) from the point of view of a '' user'' of the data, specifically in terms of possible values, possible operations on data ...
, abstract class
In object-oriented programming, a class defines the shared aspects of objects created from the class. The capabilities of a class differ between programming languages, but generally the shared aspects consist of state ( variables) and behavior ( ...
). This particular kind of type hierarchy is known, especially in the context of the Scheme language, as a '' numerical tower'', and usually contains many more types.
Object-oriented programming language
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
s offer subtype polymorphism using '' subclassing'' (also known as ''inheritance
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
''). In typical implementations, each class contains what is called a ''virtual table
In computer programming, a virtual method table (VMT), virtual function table, virtual call table, dispatch table, vtable, or vftable is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding).
Wh ...
'' (shortly called ''vtable'') — a table of functions that implement the polymorphic part of the class interface—and each object contains a pointer to the vtable of its class, which is then consulted whenever a polymorphic method is called. This mechanism is an example of:
* ''late binding
In computing, late binding or dynamic linkage—though not an identical process to dynamically linking imported code libraries—is a computer programming mechanism in which the method being called upon an object, or the function being called ...
'', because virtual function calls are not bound until the time of invocation;
* '' single dispatch'' (i.e., single-argument polymorphism), because virtual function calls are bound simply by looking through the vtable provided by the first argument (the this
object), so the runtime types of the other arguments are completely irrelevant.
The same goes for most other popular object systems. Some, however, such as Common Lisp Object System
The Common Lisp Object System (CLOS) is the facility for object-oriented programming in American National Standards Institute, ANSI Common Lisp. CLOS is a powerful dynamic programming language, dynamic object system which differs radically from t ...
, provide ''multiple dispatch
Multiple dispatch or multimethods is a feature of some programming languages in which a Subroutine, function or Method (computer programming), method can be dynamic dispatch, dynamically dispatched based on the run time (program lifecycle phase), ...
'', under which method calls are polymorphic in ''all'' arguments.
The interaction between parametric polymorphism and subtyping leads to the concepts of variance
In probability theory and statistics, variance is the expected value of the squared deviation from the mean of a random variable. The standard deviation (SD) is obtained as the square root of the variance. Variance is a measure of dispersion ...
and bounded quantification.
Row polymorphism
Row polymorphism is a similar, but distinct concept from subtyping. It deals with structural types. It allows the usage of all values whose types have certain properties, without losing the remaining type information.
Polytypism
A related concept is ''polytypism'' (or ''data type genericity''). A polytypic function is more general than polymorphic, and in such a function, "though one can provide fixed ad hoc cases for specific data types, an ad hoc combinator is absent".
Rank polymorphism
Rank polymorphism is one of the defining features of the array programming
In computer science, array programming refers to solutions that allow the application of operations to an entire set of values at once. Such solutions are commonly used in computational science, scientific and engineering settings.
Modern program ...
languages, like APL. The essence of the rank-polymorphic programming model is implicitly treating all operations as aggregate operations, usable on arrays with arbitrarily many dimensions, which is to say that rank polymorphism allows functions to be defined to operate on arrays of any shape and size.
Implementation aspects
Static and dynamic polymorphism
Polymorphism can be distinguished by when the implementation is selected: statically (at compile time) or dynamically (at run time, typically via a virtual function
In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part ...
). This is known respectively as '' static dispatch'' and ''dynamic dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
,'' and the corresponding forms of polymorphism are accordingly called ''static polymorphism'' and ''dynamic polymorphism''.
Static polymorphism executes faster, because there is no dynamic dispatch overhead, but requires additional compiler support. Further, static polymorphism allows greater static analysis by compilers (notably for optimization), source code analysis tools, and human readers (programmers). Dynamic polymorphism is more flexible but slower—for example, dynamic polymorphism allows duck typing
In computer programming, duck typing is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an object can be used for a particular purpose. With nominative ...
, and a dynamically linked library may operate on objects without knowing their full type.
Static polymorphism typically occurs in ad hoc polymorphism and parametric polymorphism, whereas dynamic polymorphism is usual for subtype polymorphism. However, it is possible to achieve static polymorphism with subtyping through more sophisticated use of template metaprogramming
Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
, namely the curiously recurring template pattern
The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a ...
.
When polymorphism is exposed via a library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
, static polymorphism becomes impossible for dynamic libraries as there is no way of knowing what types the parameters are when the shared object is built. While languages like C++ and Rust use monomorphized templates, the Swift programming language makes extensive use of dynamic dispatch to build the application binary interface
An application binary interface (ABI) is an interface exposed by software that is defined for in-process machine code access. Often, the exposing software is a library, and the consumer is a program.
An ABI is at a relatively low-level of a ...
for these libraries by default. As a result, more code can be shared for a reduced system size at the cost of runtime overhead.
See also
* 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 ...
* Virtual inheritance
References
External links
C++ examples of polymorphism
Objects and Polymorphism (Visual Prolog)
Polymorphism on MSDN
{{DEFAULTSORT:Polymorphism
Data types
Functional programming
Object-oriented programming
Programming language concepts
Type theory
Generic programming
Programming language comparisons
Articles with example C Sharp code
Articles with example Haskell code
Articles with example Java code
Articles with example Pascal code