Polymorphism (computer science): Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>NutronStar45
 
imported>Guy Harris
Give the full quote in the citation, for context, and to describe various forms of polymorphism. Define polymorphism as per that quote.
 
Line 2: Line 2:
{{Distinguish|Polymorphic code}}
{{Distinguish|Polymorphic code}}
{{Polymorphism}}
{{Polymorphism}}
In [[programming language theory]] and [[type theory]], '''polymorphism''' is the use of one symbol to represent multiple different types.<ref name="Luca">{{Cite journal |last1=Cardelli |first1=Luca |author1-link=Luca Cardelli |last2=Wegner |first2=Peter |author2-link=Peter Wegner (computer scientist)|doi=10.1145/6041.6042 |title=On understanding types, data abstraction, and polymorphism |journal=[[ACM Computing Surveys]] |volume=17 |issue=4 |pages=471–523 |date=December 1985 |url=http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf |citeseerx=10.1.1.117.695 |s2cid=2921816}}: "Polymorphic types are types whose operations are applicable to values of more than one type."</ref>
In [[programming language theory]] and [[type theory]], '''polymorphism''' allows a value or variable to have more than one type and allows a given operation to be performed on values of more than one type.<ref name="Luca">{{Cite journal |last1=Cardelli |first1=Luca |author1-link=Luca Cardelli |last2=Wegner |first2=Peter |author2-link=Peter Wegner (computer scientist)|doi=10.1145/6041.6042 |title=On understanding types, data abstraction, and polymorphism |journal=[[ACM Computing Surveys]] |volume=17 |issue=4 |pages=471–523 |date=December 1985 |url=http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf |citeseerx=10.1.1.117.695 |s2cid=2921816 |quote=Conventional typed languages, such as Pascal, are based on the idea that functions and procedures, and hence their operands, have a unique type. Such languages are said to be ''monomorphic'', in the sense that every value and variable can be interpreted to be of one and only one type. Monomorphic programming languages may be contrasted with ''polymorphic'' languages in which some values and variables may have more than one type. Polymorphic functions are functions whose operands (actual parameters) can have more than one type. Polymorphic types are types whose operations are applicable to values of more than one type.}}</ref>


In [[object-oriented programming]], polymorphism is the provision of one [[Interface (object-oriented programming)|interface]] to entities of different [[data type]]s.<ref>{{cite web |url=http://www.stroustrup.com/glossary.html#Gpolymorphism |last1=Stroustrup |first1=Bjarne |author1-link=Bjarne Stroustrup |title=Bjarne Stroustrup's C++ Glossary |date=February 19, 2007 |quote=polymorphism – providing a single interface to entities of different types.}}</ref>  The concept is borrowed from a principle in [[biology]] where an organism or species can have many different forms or stages.<ref name="Moved">{{cite web |title=Polymorphism |work=The Java Tutorials: Learning the Java Language: Interfaces and Inheritance |publisher=Oracle |url=https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html |access-date=2021-09-08}}</ref>
In [[object-oriented programming]], polymorphism is the provision of one [[Interface (object-oriented programming)|interface]] to entities of different [[data type]]s.<ref>{{cite web |url=http://www.stroustrup.com/glossary.html#Gpolymorphism |last1=Stroustrup |first1=Bjarne |author1-link=Bjarne Stroustrup |title=Bjarne Stroustrup's C++ Glossary |date=February 19, 2007 |quote=polymorphism – providing a single interface to entities of different types.}}</ref>  The concept is borrowed from a principle in [[biology]] in which an organism or species can have many different forms or stages.<ref name="Moved">{{cite web |title=Polymorphism |work=The Java Tutorials: Learning the Java Language: Interfaces and Inheritance |publisher=Oracle |url=https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html |access-date=2021-09-08}}</ref>


The most commonly recognized major forms of polymorphism are:
The most commonly recognized major forms of polymorphism are:
* ''[[Ad hoc polymorphism]]'': defines a common interface for an arbitrary set of individually specified types.
* ''[[Ad hoc polymorphism]]'': defines a common interface for an arbitrary set of individually specified types.
* ''[[Parametric polymorphism]]'': not specifying concrete types and instead use abstract symbols that can substitute for any type.
* ''[[Parametric polymorphism]]'': does not specify concrete types and instead uses abstract symbols that can substitute for any type.
* ''[[Subtyping]]'' (also called ''subtype polymorphism'' or ''inclusion polymorphism''): when a name denotes instances of many different classes related by some common superclass.<ref name="gbooch">{{cite book |last1=Conallen |first1=J. |last2=Engle |first2=M. |last3=Houston |first3=K. |last4=Maksimchuk |first4=R. |last5=Young |first5=B. |last6=Booch |first6=G. |author6-link=Grady Booch |date=2007 |title=Object-Oriented Analysis and Design with Applications |publisher=Pearson Education |edition=3rd |isbn=9780132797443 |pages=}}</ref>
* ''[[Subtyping]]'' (also called ''subtype polymorphism'' or ''inclusion polymorphism''): when a name denotes instances of many different classes related by a common superclass.<ref name="gbooch">{{cite book |last1=Conallen |first1=J. |last2=Engle |first2=M. |last3=Houston |first3=K. |last4=Maksimchuk |first4=R. |last5=Young |first5=B. |last6=Booch |first6=G. |author6-link=Grady Booch |date=2007 |title=Object-Oriented Analysis and Design with Applications |publisher=Pearson Education |edition=3rd |isbn=9780132797443 |pages=}}</ref>


==History==
==History==
Interest in polymorphic [[type system]]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]]'s ''[[Fundamental Concepts in Programming Languages]]'',<ref name=Strachey00>{{cite journal |last1=Strachey |first1=Christopher |author1-link=Christopher Strachey |date=2000 |title=Fundamental Concepts in Programming Languages |journal=[[Higher-Order and Symbolic Computation]] |volume=13 |issue=1/2 |pages=11–49 |doi=10.1023/A:1010000313106 |issn=1573-0557 |citeseerx=10.1.1.332.3161 |s2cid=14124601}}</ref> where they are listed as "the two main classes" of polymorphism. Ad hoc polymorphism was a feature of [[ALGOL 68]], while parametric polymorphism was the core feature of [[ML (programming language)|ML]]'s [[type system]].
Interest in polymorphic [[type system]]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]]'s ''[[Fundamental Concepts in Programming Languages]]'',<ref name=Strachey00>{{cite journal |last1=Strachey |first1=Christopher |author1-link=Christopher Strachey |date=2000 |title=Fundamental Concepts in Programming Languages |journal=[[Higher-Order and Symbolic Computation]] |volume=13 |issue=1/2 |pages=11–49 |doi=10.1023/A:1010000313106 |issn=1573-0557 |citeseerx=10.1.1.332.3161 |s2cid=14124601}}</ref> where they are listed as "the two main classes" of polymorphism. Ad hoc polymorphism was a feature of [[ALGOL 68]], while parametric polymorphism was the core feature of [[ML (programming language)|ML]]'s [[type system]].


In a 1985 paper, [[Peter Wegner (computer scientist)|Peter Wegner]] and [[Luca Cardelli]] introduced the term ''inclusion polymorphism'' to model subtypes and [[Inheritance (object-oriented programming)|inheritance]],<ref name="Luca"/> citing [[Simula]] as the first programming language to implement it.
In a 1985 paper, [[Peter Wegner (computer scientist)|Peter Wegner]] and [[Luca Cardelli]] introduced the term ''inclusion polymorphism'' to model subtypes and [[Inheritance (object-oriented programming)|inheritance]],<ref name="Luca"/> citing [[Simula]] as the first programming language to implement it.
Line 19: Line 19:
===Ad hoc polymorphism===
===Ad hoc polymorphism===
{{Further|Ad hoc polymorphism}}
{{Further|Ad hoc polymorphism}}
[[Christopher Strachey]] 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]] or [[operator overloading]]).<ref name=Strachey00/> The term "[[ad hoc]]" 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 (programming language)|Java]] example below, the <code>add</code> functions seem to work generically over two types ([[Integer (computer science)|integer]] and [[String (computer science)|string]]) when looking at the invocations, but are considered to be two entirely distinct functions by the [[compiler]] for all intents and purposes:
[[Christopher Strachey]] 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]] or [[operator overloading]]).<ref name=Strachey00/> The term "[[ad hoc]]" in this context is not pejorative. Rather, it means that this form of polymorphism is not a fundamental feature of the type system. In the [[Java (programming language)|Java]] example below, the <code>add</code> functions seem to work generically over two types ([[Integer (computer science)|integer]] and [[String (computer science)|string]]) when looking at the invocations, but are considered entirely distinct functions by the [[compiler]]:


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
class AdHocPolymorphic {
class AdHocPolymorphic {
     public String add(int x, int y) {
     public String add(int x, int y) {
         return "Sum: " + (x + y);
         return String.format("Sum: %d", x + y);
     }
     }


     public String add(String name) {
     public String add(String name) {
         return "Added " + name;
         return String.format("Added ", name);
     }
     }
}
}
Line 36: Line 36:
         AdHocPolymorphic poly = new AdHocPolymorphic();
         AdHocPolymorphic poly = new AdHocPolymorphic();


         System.out.println(poly.add(1,2));  // prints "Sum: 3"
         System.out.println(poly.add(1, 2));  // prints "Sum: 3"
         System.out.println(poly.add("Jay")); // prints "Added Jay"
         System.out.println(poly.add("Jay")); // prints "Added Jay"
     }
     }
Line 42: Line 42:
</syntaxhighlight>
</syntaxhighlight>


In [[dynamically typed]] languages the situation can be more complex as the correct function that needs to be invoked might only be determinable at run time.
In [[dynamically typed]] 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]] has also been defined as a form of polymorphism, referred to as "coercion polymorphism".<ref name="Luca"/><ref name="Tucker2004">{{cite book |last1=Tucker |first1=Allen B.|date=2004 |title=Computer Science Handbook |edition=2nd |url=https://books.google.com/books?id=9IFMCsQJyscC&pg=SA91-PA5 |publisher=Taylor & Francis |pages=91– |isbn=978-1-58488-360-9}}</ref>
[[Implicit type conversion]] has also been defined as a form of polymorphism, referred to as "coercion polymorphism".<ref name="Luca"/><ref name="Tucker2004">{{cite book |last1=Tucker |first1=Allen B.|date=2004 |title=Computer Science Handbook |edition=2nd |url=https://books.google.com/books?id=9IFMCsQJyscC&pg=SA91-PA5 |publisher=Taylor & Francis |pages=91– |isbn=978-1-58488-360-9}}</ref>
Line 66: Line 66:
</syntaxhighlight>
</syntaxhighlight>


Parametric polymorphism is also available in several object-oriented languages. For instance, [[Template (C++)|templates]] in [[C++]] and [[D (programming language)|D]], or under the name [[Generics in Java|generics]] in [[C Sharp (programming language)|C#]], [[Delphi (software)|Delphi]], Java, and [[Go (programming language)|Go]]:
Parametric polymorphism is also available in several object-oriented languages. For instance, [[Template (C++)|templates]] in [[C++]] and [[D (programming language)|D]], or under the name [[Generics in Java|generics]] in [[C Sharp (programming language)|C#]], [[Delphi (software)|Delphi]], [[Java (programming language)|Java]], and [[Go (programming language)|Go]]:


<syntaxhighlight lang="CSharp">
<syntaxhighlight lang="CSharp">
Line 87: Line 87:
===Subtyping===
===Subtyping===
{{Further|Subtyping}}
{{Further|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 {{nowrap|''S'' <: ''T''}}. Conversely, ''T'' is said to be a ''supertype'' of ''S'', written {{nowrap|''T'' :> ''S''}}. Subtype polymorphism is usually resolved dynamically (see below).
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 {{nowrap|''S'' <: ''T''}}. Conversely, ''T'' is said to be a ''supertype'' of ''S'', written {{nowrap|''T'' :> ''S''}}. Subtype polymorphism is usually resolved dynamically (see below).


In the following Java example cats and dogs are made subtypes of pets. The procedure <code>letsHear()</code> accepts a pet, but will also work correctly if a subtype is passed to it:
In the following Java example cats and dogs are made subtypes of pets. The procedure <code>letsHear()</code> accepts a pet, but will also work correctly if a subtype is passed to it:
Line 109: Line 109:


static void letsHear(final Pet pet) {
static void letsHear(final Pet pet) {
     println(pet.speak());
     System.out.println(pet.speak());
}
}


Line 120: Line 120:
[[File:UML class pet.svg]]
[[File:UML class pet.svg]]


In another example, if ''Number'', ''Rational'', and ''Integer'' are types such that {{nowrap|''Number'' :> ''Rational''}} and {{nowrap|''Number'' :> ''Integer''}} (''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]], and accessed via object [[identity (object-oriented programming)|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]], [[abstract class]]). This particular kind of type hierarchy is known, especially in the context of the [[Scheme (programming language)|Scheme language]], as a ''[[numerical tower]]'', and usually contains many more types.
In another example, if ''Number'', ''Rational'', and ''Integer'' are types such that {{nowrap|''Number'' :> ''Rational''}} and {{nowrap|''Number'' :> ''Integer''}} (''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]], and accessed via object [[identity (object-oriented programming)|identity]]. If the ''Number'' type is ''abstract'', it may not be possible to access an object whose ''most-derived'' type is ''Number'' (see [[abstract data type]], [[abstract class]]). This particular kind of type hierarchy is known, especially in the context of the [[Scheme (programming language)|Scheme language]], as a ''[[numerical tower]]'', and usually contains many more types.


[[Object-oriented programming language]]s offer subtype polymorphism using ''[[Subclass (computer science)|subclass]]ing'' (also known as ''[[inheritance in object-oriented programming|inheritance]]''). In typical implementations, each class contains what is called a ''[[virtual table]]'' (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:
[[Object-oriented programming language]]s offer subtype polymorphism using ''[[Subclass (computer science)|subclass]]ing'' (also known as ''[[inheritance in object-oriented programming|inheritance]]''). In typical implementations, each class contains what is called a ''[[virtual table]]'' (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]]'', because virtual function calls are not bound until the time of invocation;
* ''[[late binding]]'', 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 <code>this</code> object), so the runtime types of the other arguments are completely irrelevant.
* ''[[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 <code>this</code> 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]], provide ''[[multiple dispatch]]'', under which method calls are polymorphic in ''all'' arguments.
The same goes for most other popular object systems. Some, however, such as [[Common Lisp Object System]], provide ''[[multiple dispatch]]'', under which method calls are polymorphic in all arguments.


The interaction between parametric polymorphism and subtyping leads to the concepts of [[covariance and contravariance (computer science)|variance]] and [[bounded quantification]].
The interaction between parametric polymorphism and subtyping leads to the concepts of [[covariance and contravariance (computer science)|variance]] and [[bounded quantification]].

Latest revision as of 22:25, 22 December 2025

Template:Short description Script error: No such module "Distinguish". Template:Polymorphism In programming language theory and type theory, polymorphism allows a value or variable to have more than one type and allows a given operation to be performed on values of more than one type.[1]

In object-oriented programming, polymorphism is the provision of one interface to entities of different data types.[2] The concept is borrowed from a principle in biology in which an organism or species can have many different forms or stages.[3]

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: does not specify concrete types and instead uses abstract symbols that can substitute for any type.
  • Subtyping (also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by a common superclass.[4]

History

Interest in polymorphic type systems 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's Fundamental Concepts in Programming Languages,[5] where they are listed as "the two main classes" of polymorphism. Ad hoc polymorphism was a feature of ALGOL 68, while parametric polymorphism was the core feature of ML's type system.

In a 1985 paper, Peter Wegner and Luca Cardelli introduced the term inclusion polymorphism to model subtypes and inheritance,[1] citing Simula as the first programming language to implement it.

Forms

Ad hoc polymorphism

Script error: No such module "labelled list hatnote". Christopher Strachey 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 or operator overloading).[5] The term "ad hoc" in this context is not pejorative. Rather, it means that this form of polymorphism is not a fundamental feature of the type system. In the Java example below, the add functions seem to work generically over two types (integer and string) when looking at the invocations, but are considered entirely distinct functions by the compiler:

class AdHocPolymorphic {
    public String add(int x, int y) {
        return String.format("Sum: %d", x + y);
    }

    public String add(String name) {
        return String.format("Added ", name);
    }
}

public class Adhoc {
    public static void main(String[] args) {
        AdHocPolymorphic poly = new AdHocPolymorphic();

        System.out.println(poly.add(1, 2));   // prints "Sum: 3"
        System.out.println(poly.add("Jay")); // prints "Added Jay"
    }
}

In dynamically typed 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 has also been defined as a form of polymorphism, referred to as "coercion polymorphism".[1][6]

Parametric polymorphism

Script error: No such module "labelled list hatnote". 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.[7] Parametric polymorphism is a way to make a language more expressive while still maintaining full static type safety.

The concept of parametric polymorphism applies to both data types 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 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 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, Java, and Go:

class List<T> {
    class Node<T> {
        T elem;
        Node<T> next;
    }
    Node<T> head;
    int length() { ... }
}

List<B> map(Func<A, B> f, List<A> xs) {
    ...
}

John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to lambda calculus (called the polymorphic lambda calculus or System F). 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

Script error: No such module "labelled list hatnote". 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 S <: T. Conversely, T is said to be a supertype of S, written T :> S. 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 {
    abstract String speak();
}

class Cat extends Pet {
    String speak() {
        return "Meow!";
    }
}

class Dog extends Pet {
    String speak() {
        return "Woof!";
    }
}

static void letsHear(final Pet pet) {
    System.out.println(pet.speak());
}

static void main(String[] args) {
    letsHear(new Cat());
    letsHear(new Dog());
}

File:UML class pet.svg

In another example, if Number, Rational, and Integer are types such that Number :> Rational and Number :> Integer (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, and accessed via object identity. If the Number type is abstract, it may not be possible to access an object whose most-derived type is Number (see abstract data type, abstract class). 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 languages offer subtype polymorphism using subclassing (also known as inheritance). In typical implementations, each class contains what is called a virtual table (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, 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, provide multiple dispatch, under which method calls are polymorphic in all arguments.

The interaction between parametric polymorphism and subtyping leads to the concepts of variance and bounded quantification.

Row polymorphism

Script error: No such module "labelled list hatnote". Script error: No such module "Labelled list hatnote".

Row polymorphism[8] 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

Script error: No such module "labelled list hatnote". 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".[9]

Rank polymorphism

Rank polymorphism is one of the defining features of the array programming 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,[10] 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

Script error: No such module "labelled list hatnote".

Polymorphism can be distinguished by when the implementation is selected: statically (at compile time) or dynamically (at run time, typically via a virtual function). This is known respectively as static dispatch and dynamic dispatch, 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, 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, namely the curiously recurring template pattern.

When polymorphism is exposed via a library, 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 for these libraries by default. As a result, more code can be shared for a reduced system size at the cost of runtime overhead.[11]

See also

References

<templatestyles src="Reflist/styles.css" />

  1. a b c Script error: No such module "Citation/CS1".
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. Script error: No such module "citation/CS1".
  5. a b Script error: No such module "Citation/CS1".
  6. Script error: No such module "citation/CS1".
  7. Script error: No such module "citation/CS1".
  8. Script error: No such module "citation/CS1".
  9. Script error: No such module "citation/CS1".
  10. Script error: No such module "citation/CS1".
  11. Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".

External links

Template:Data types