Information about Type Polymorphism

The Greek meaning of the words "poly" and "morph" together imply that "a single entity can take on multiple forms". In the field of computer science, there are two fundamentally different types of polymorphism; subtype polymorphism, and parametric polymorphism. A concrete example can be found in the C++ language. In C++, subtype polymorphism is realized via the inheritance mechanism, and is also known as runtime polymorphism or dynamic polymorphism. In C++, parametric polymorphism is realized via the template mechanism and is also known as compile time polymorphism or static polymorphism. If one does not know what 'multiple form' an entity will take on until runtime, then inheritance is the only mechanism of choice. If, however, one or more specific examples of the possible "multiple forms" is known at compile time, template polymorphism can be used as well as inheritance polymorphism.

The C++ Standard Template Library (STL), for example, makes heavy use of parametric polymorphic behavior. One of the greatest accomplishments of the STL has been to provide for loose coupling between data structures and algorithms that use them, by parameterizing the data accessor constructs known as iterators . One would not be entirely incorrect to think of an iterator as an extension of the pointer concept. The key difference being that the iterator's type (or types; remember, single entity taking on multiple forms, even simultaneously) is determined at compile time.



In computer science, polymorphism is the use of a general interface to manipulate things of various specialized types. The concept of 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 is known as a polymorphic data type as is the generalized type from which such specializations are made.

There are two fundamentally different kinds of polymorphism, as first informally described by Christopher Strachey in 1967. If the range of actual types that can be used is finite and the combinations must be specified individually prior to use, it is called ad-hoc polymorphism. If all code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism. In their formal treatment of the topic in 1985, Luca Cardelli and Peter Wegner later restricted the term parametric polymorphism to instances with type parameters, recognizing also other kinds of universal polymorphism.

Programming using parametric polymorphism is called generic programming, particularly in the object-oriented community. Advocates of object-oriented programming often cite polymorphism as one of the major benefits of that paradigm over others. Advocates of functional programming reject this claim on the grounds that the notion of parametric polymorphism is so deeply ingrained in many statically typed functional programming languages that most programmers simply take it for granted. However, the rise in popularity of object-oriented programming languages did contribute greatly to awareness and use of polymorphism in the mainstream programming community. (See polymorphism in object-oriented programming for details.)

Polymorphism in Strongly-Typed Languages

Parametric polymorphism

Parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without depending on their type.[1]

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, OCaml, Haskell, Visual Prolog and others. Java and C# have both recently introduced "generics" for parametric polymorphism.

The most general form of polymorphism is "higher-rank impredicative polymorphism". Two popular restrictions of this form are restricted rank polymorphism (for example, rank-1 or prenex polymorphism) and predicative polymorphism. Together, these restrictions give "predicative prenex polymorphism", which is essentially the form of polymorphism found in ML and early versions of Haskell.

Rank Restrictions

Rank-1 (Prenex) Polymorphism


In a prenex polymorphic system, type variables may not be instantiated with polymorphic types. 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 is that all types can be written in a form which places all quantifiers at the outermost (prenex) position.

For example, consider the append function described above, which has type [a] Ã— [a] → [a]; in order to apply this function to a pair of lists, a type must be substituted for the variable a in the type of the function such that the type of the arguments matches up with the resulting function type. In an impredicative system, the type being substituted may be any type whatsoever, including a type that is itself polymorphic; thus append can be applied to pairs of lists with elements of any type -- even to lists of polymorphic functions such as append itself.

Polymorphism in the language ML and its close relatives is predicative. This is because predicativity, together with other restrictions, makes the type system simple enough that type inference is possible. In languages where explicit type annotations are necessary when applying a polymorphic function, the predicativity restriction is less important; thus these languages are generally impredicative. Haskell manages to achieve type inference without predicativity but with a few complications.
Rank-k Polymorphism


For some fixed value , rank-k polymorphism is a system in which a quantifier may not appear to the left of more than arrows (when the type is drawn as a tree)[1].

Type reconstruction for rank-2 polymorphism is decidable, but reconstruction for rank-3 and above is not.
Rank-n ("Higher-rank") Polymorphism


Rank-n polymorphism refers to polymorphism in which quantifiers may appear to the left of arbitrarily many arrows.

Predicativity Restrictions

Predicative Polymorphism


In a predicative parametric polymorphic system, a type containing a type variable may not be used in such a way that is instantiated to itself.
Impredicative Polymorphism ("First Class" Polymorphism)


Also called First-class polymorphism. Impredicative polymorphism allows the instantiation of a variable in a type with the type itself.

In type theory, the most frequently studied impredicative typed λ-calculi are based on those of the lambda cube, especially System F. Predicative type theories include Martin-Löf Type Theory and NuPRL.

Bounded Parametric Polymorphism

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 (see #Subtyping polymorphism below and the article on Generic programming).

Subtype Polymorphism

Subtyping polymorphism

Some languages employ the idea of subtypes to restrict the range of types that can be used in a particular case of parametric polymorphism. In these languages, subtyping polymorphism (sometimes referred to as dynamic polymorphism) 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.

For example, if Number, Rational, and Integer are types such that Number :> Rational and Number :> Integer, 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. In fact, 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—as a numerical tower, and usually contains a lot more types.

Object-oriented programming languages offer subtyping polymorphism using subclassing (also known as inheritance). In typical implementations, each class contains what is called a virtual table—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, and
  • 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 CLOS, provide multiple dispatch, under which method calls are polymorphic in all arguments.

Ad-hoc polymorphism



Strachey [2] chose the term ad-hoc polymorphism to refer to polymorphic functions which can be applied to arguments of different types, but which behave differently depending on the type of the argument to which they are applied (also known as function overloading). The term "ad hoc" in this context is not intended to be pejorative; it refers simply to the fact that this type of polymorphism is not a fundamental feature of the type system.

Ad-hoc polymorphism is a dispatch mechanism: code moving through one named function is dispatched to various other functions without having to specify the exact function being called. Overloading allows multiple functions taking different types to be defined with the same name; the compiler or interpreter automatically calls the right one. This way, functions appending lists of integers, lists of strings, lists of real numbers, and so on could be written, and all be called append—and the right append function would be called based on the type of lists being appended. This differs from parametric polymorphism, in which the function would need to be written generically, to work with any kind of list. Using overloading, it is possible to have a function perform two completely different things based on the type of input passed to it; this is not possible with parametric polymorphism. Another way to look at overloading is that a routine is uniquely identified not by its name, but by the combination of its name and the number, order and types of its parameters.

This type of polymorphism is common in object-oriented programming languages, many of which allow operators to be overloaded in a manner similar to functions (see operator overloading). It is also used extensively in the purely functional programming language Haskell in the form of type classes. Some languages which are not dynamically typed and lack ad-hoc polymorphism (including type classes) have longer function names such as print_int, print_string, etc. This can be seen as advantage (more descriptive) or a disadvantage (more long-winded) depending on one's point of view.

An advantage that is sometimes gained from overloading is the appearance of specialization, e.g., a function with the same name can be implemented in multiple different ways, each optimized for the particular data types that it operates on. This can provide a convenient interface for code that needs to be specialized to multiple situations for performance reasons.

Since overloading is done at compile time, it is not a substitute for late binding as found in subtyping polymorphism.

Example

This example aims to illustrate three different kinds of polymorphism described in this article. Though overloading an originally arithmetic operator to do a wide variety of things in this way may not be the most clear-cut example, it allows some subtle points to be made. In practice, the different types of polymorphism are not generally mixed up as much as they are here.

Imagine, if you will, an operator + that may be used in the following ways:
  1. 1 + 2 = 3
  2. 3.14 + 0.0015 = 3.1415
  3. 1 + 3.7 = 4.7
  4. [1, 2, 3] + [4, 5, 6] = [1, 2, 3, 4, 5, 6]
  5. [true, false] + [false, true] = [true, false, false, true]
  6. "foo" + "bar" = "foobar"

Overloading

To handle these six function calls, four different pieces of code are needed—or three, if strings are considered to be lists of characters:
  • In the first case, integer addition must be invoked.
  • In the second and third cases, floating-point addition must be invoked.
  • In the fourth and fifth cases, list concatenation must be invoked.
  • In the last case, string concatenation must be invoked, unless this too is handled as list concatenation (e.g., Haskell).
Thus, the name + actually refers to three or four completely different functions. This is an example of overloading.

Override polymorphism

This sometimes called override of existing code. Subclasses of existing classes are given a "replacement method" for methods in the superclass. Superclass objects may also use replacement method when dealing with objects of the new type. The replacement method that a subclass provides, has the signature exactly same as the original method in the superclass (return type, number and type of parameters etc)

Java API Example: For Java, every object is a subclass of Object. Object is a superclass of BigDecimal. Thus when implementing BigDecimal, the author overrides the method toString() .

BigDecimal.toString() overrides Object.toString()

Example below


Object no = new java.math.BigDecimal("0.0"); System.out.println(no.toString());
BigDecimal bd = new java.math.BigDecimal("0.0"); System.out.println(bd.toString());
//BigDecimal bd2 = new Object(); - > illegal //System.out.println(bd2.toString());
Object no2 = new Object(); System.out.println(no2.toString());

Output is:
0.0 0.0 java.lang.Object@86c347

Parametric polymorphism

Finally, the reason why we can concatenate both lists of integers, lists of booleans, and lists of characters, is that the function for list concatenation was written without any regard to the type of elements stored in the lists. This is an example of parametric polymorphism. If you wanted to, you could make up a thousand different new types of lists, and the generic list concatenation function would happily and without requiring any augmentation accept instances of them all.

It can be argued, however, that this polymorphism is not really a property of the function per se; that if the function is polymorphic, it is due to the fact that the list data type is polymorphic. This is true—to an extent, at least—but it is important to note that the function could just as well have been defined to take as a second argument an element to append to the list, instead of another list to concatenate to the first. If this were the case, the function would indisputably be parametrically polymorphic, because it could then not know anything about its second argument, except that the type of the element should match the type of the elements of the list.

See also

References

1. ^ Pierce, B. C. 2002 Types and Programming Languages. MIT Press.
2. ^ C. Strachey, Fundamental concepts in programming languages. Lecture notes for International Summer School in Computer Programming, Copenhagen, August 1967

External links

Computer science, or computing science, is the study of the theoretical foundations of information and computation and their implementation and application in computer systems.
..... Click the link for more information.
In programming languages a data type defines a set of values and the allowable operations on those values[1]. For example, in the Java programming language, the "int" type represents the set of 32-bit integers ranging in value from -2,147,483,648 to 2,147,483,647, and
..... Click the link for more information.
In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code.
..... Click the link for more information.
Christopher Strachey (1916–1975) was a British computer scientist. He was one of the founders of denotational semantics, and a pioneer in programming language design. He was a member of the Strachey family prominent in government, arts, administration and academia.
..... Click the link for more information.
19th century - 20th century - 21st century
1930s  1940s  1950s  - 1960s -  1970s  1980s  1990s
1964 1965 1966 - 1967 - 1968 1969 1970

Year 1967 (MCMLXVII
..... Click the link for more information.
Ad hoc is a Latin phrase which means "for this purpose". It generally signifies a solution that has been custom designed for a specific problem, is non-generalizable, and cannot be adapted to other purposes.
..... Click the link for more information.
Parametric may refer to:
  • Parametric equation
  • Parametric statistics
  • Parametric derivative
  • Parametric plot
  • Parametric model
  • Parametric resonance
  • Parametric contract
  • Parametric insurance
  • Spontaneous parametric down conversion

..... Click the link for more information.
20th century - 21st century
1950s  1960s  1970s  - 1980s -  1990s  2000s  2010s
1982 1983 1984 - 1985 - 1986 1987 1988

Year 1985 (MCMLXXXV) was a common year starting on Tuesday (link displays 1985 Gregorian calendar).
..... Click the link for more information.
Luca Cardelli is an Italian computer scientist who is currently an Assistant Director at Microsoft Research in Cambridge, UK. Cardelli is well-known for his research in type theory and operational semantics.
..... Click the link for more information.
Generic programming is a style of computer programming where algorithms are written in an extended grammar and are made adaptable by specifying variable parts that are then somehow instantiated later by the compiler with respect to the base grammar.
..... Click the link for more information.
Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.
..... Click the link for more information.
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.
..... Click the link for more information.
In computer science, a type system defines how a programming language classifies values and expressions into types, how it can manipulate those types and how they interact.
..... Click the link for more information.
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.
..... Click the link for more information.
In simple terms, polymorphism lets you treat derived class members just like their parent class's members.

More precisely, polymorphism (object-oriented programming theory) is the ability of objects belonging to different types to respond to method calls of the same name,
..... Click the link for more information.
In computer science, type safety is a property attributed to some, but not all, programming languages. The term is defined differently by different communities who use it — in particular, the formal type-theoretic definition is considerably stronger than what is understood by
..... Click the link for more information.
Parametric may refer to:
  • Parametric equation
  • Parametric statistics
  • Parametric derivative
  • Parametric plot
  • Parametric model
  • Parametric resonance
  • Parametric contract
  • Parametric insurance
  • Spontaneous parametric down conversion

..... Click the link for more information.
ML
Paradigm: multi-paradigm: imperative, functional
Appeared in: 1973
Designed by: Robin Milner & others at the University of Edinburgh
Typing discipline: static, strong, inferred
Dialects: Standard ML, OCaml, F#
Influenced by: ISWIM
..... Click the link for more information.
19th century - 20th century - 21st century
1940s  1950s  1960s  - 1970s -  1980s  1990s  2000s
1973 1974 1975 - 1976 - 1977 1978 1979

Year 1976 (MCMLXXVI
..... Click the link for more information.
Standard ML
Paradigm: multi-paradigm: functional, imperative
Typing discipline: strong, static
Major implementations: MLton, MLWorks, Moscow ML, Poly/ML, SML/NJ, SML.
..... Click the link for more information.
Objective Caml

Paradigm: multi-paradigm: imperative, functional, object-oriented
Developer: INRIA
Latest release: 3.10.0/ May 16, 2007
Dialects: JoCaml, Metaocaml, Ocamlp3l
Influenced by: Caml Light, Standard ML
Influenced: Scala
..... Click the link for more information.
Haskell

Paradigm: functional, non-strict, modular
Appeared in: 1990
Designed by: Simon Peyton-Jones, Paul Hudak[1], Philip Wadler, et al
Typing discipline: static, strong, inferred
Major implementations: GHC, Hugs, NHC , JHC , Yhc
..... Click the link for more information.
Visual Prolog, also formerly known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. As Turbo Prolog it was marketed by Borland, but it is now developed and marketed by the Danish firm Prolog Development Center (PDC) that originally developed
..... Click the link for more information.
Java
Native name: Jawa<nowiki />

Topography of Java

Geography
<nowiki/>
Location Southeast Asia
Coordinates <nowiki />
Archipelago
..... Click the link for more information.
C#
Paradigm: structured, imperative, object-oriented
Appeared in: 2001 (last revised 2005)
Designed by: Microsoft Corporation
Typing discipline: static, strong, both safe and unsafe, nominative
Major implementations: .NET Framework, Mono, DotGNU
Dialects: 1.
..... Click the link for more information.
Type inference is a feature present in some strongly statically typed programming languages. It is often characteristic of — but not limited to — functional programming languages in general.
..... Click the link for more information.

..... Click the link for more information.
In mathematics, logic and computer science, type theory is any of several formal systems that can serve as alternatives to naive set theory, or the study of such formalisms in general.
..... Click the link for more information.
A typed lambda calculus is a typed formalism that uses the lambda-symbol () to denote anonymous function abstraction. Typed lambda calculi are foundational programming languages and are the base of typed functional programming languages such as ML and Haskell and, more indirectly,
..... Click the link for more information.
In mathematical logic and type theory, the λ-cube is a framework for exploring the axes of refinement in Coquand's calculus of constructions, starting from the simply typed lambda calculus as the vertex of a cube placed at the origin, and the calculus of constructions (higher
..... Click the link for more information.


This article is copied from an article on Wikipedia.org - the free encyclopedia created and edited by online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of the wikipedia encyclopedia articles provide accurate and timely information please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.
Herod_Archelaus


page counter