Polymorphism (computer science)

In programming language theory and type theory, polymorphism is the use of one symbol to represent multiple different types.[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 where 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: not specifying concrete types and instead use 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.[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

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: instead, 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 to be two entirely distinct functions by the compiler for all intents and purposes:

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

    public String add(String name) {
        return "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

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

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) {
    println(pet.speak());
}

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

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 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 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

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

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

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

  1. ^ a b c Cardelli, Luca; Wegner, Peter (December 1985). "On understanding types, data abstraction, and polymorphism" (PDF). ACM Computing Surveys. 17 (4): 471–523. CiteSeerX 10.1.1.117.695. doi:10.1145/6041.6042. S2CID 2921816.: "Polymorphic types are types whose operations are applicable to values of more than one type."
  2. ^ Stroustrup, Bjarne (February 19, 2007). "Bjarne Stroustrup's C++ Glossary". polymorphism – providing a single interface to entities of different types.
  3. ^ "Polymorphism". The Java Tutorials: Learning the Java Language: Interfaces and Inheritance. Oracle. Retrieved 2021-09-08.
  4. ^ Conallen, J.; Engle, M.; Houston, K.; Maksimchuk, R.; Young, B.; Booch, G. (2007). Object-Oriented Analysis and Design with Applications (3rd ed.). Pearson Education. ISBN 9780132797443.
  5. ^ a b Strachey, Christopher (2000). "Fundamental Concepts in Programming Languages". Higher-Order and Symbolic Computation. 13 (1/2): 11–49. CiteSeerX 10.1.1.332.3161. doi:10.1023/A:1010000313106. ISSN 1573-0557. S2CID 14124601.
  6. ^ Tucker, Allen B. (2004). Computer Science Handbook (2nd ed.). Taylor & Francis. pp. 91–. ISBN 978-1-58488-360-9.
  7. ^ Pierce, B.C. (2002). "23.2 Varieties of Polymorphism". Types and Programming Languages. MIT Press. pp. 340–1. ISBN 9780262162098.
  8. ^ Wand, Mitchell (June 1989). "Type inference for record concatenation and multiple inheritance". Proceedings. Fourth Annual Symposium on Logic in Computer Science. pp. 92–97. doi:10.1109/LICS.1989.39162.
  9. ^ Lämmel, Ralf; Visser, Joost (2002). "Typed Combinators for Generic Traversal". Practical Aspects of Declarative Languages: 4th International Symposium. Springer. pp. 137–154, See p. 153. CiteSeerX 10.1.1.18.5727. ISBN 354043092X.
  10. ^ Slepak, Justin; Shivers, Olin; Manolios, Panagiotis (2019). "The semantics of rank polymorphism". arXiv:1907.00509 [cs.PL].
  11. ^ Beingessner, Alexis. "How Swift Achieved Dynamic Linking Where Rust Couldn't".

Read other articles:

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Tiong Se Academy – news · newspapers · books · scholar · JSTOR (June 2015) (Learn how and when to remove this template message) Tiong Se Academy中西学院LocationBinondoManila, Metro ManilaPhilippinesCoordinates14°36′13″N 120°58′21″E / þ...

 

 

У этого термина существуют и другие значения, см. Учитель года. Учитель года России — ежегодный всероссийский конкурс, который проводится Министерством просвещения Российской Федерации, Общероссийским профсоюзом образования и «Учительской газетой». Целью конкурса я

 

 

Ця стаття є частиною Проєкту:Населені пункти України (рівень: невідомий) Портал «Україна»Мета проєкту — покращувати усі статті, присвячені населеним пунктам та адміністративно-територіальним одиницям України. Ви можете покращити цю статтю, відредагувавши її, а на стор...

Bahlui RiverBahlui River in IaşiLokasi di RumaniaLokasiNegaraRumaniaKotaHârlău, IaşiDistrikBotoşani County,Iaşi CountyCiri-ciri fisikHulu sungai  - lokasiTudora - elevasi500 meter (1.600 ft) Muara sungaiJijia River - lokasiChipereştiPanjang119 meter (390 ft)Debit air  - rata-rata28 meter kubik per detik (990 cu ft/s) Daerah Aliran SungaiLuas DASDAS: 2007Official River CodeXIII.15.32 Sungai Bahlui adalah sungai terbes...

 

 

1936 film by Alfred Zeisler The Amazing Quest of Ernest BlissA DVD issue of the film, under the US titleDirected byAlfred ZeislerWritten byJohn L. Balderston (writer)E. Phillips Oppenheim (novel)Produced byAlfred ZeislerStarringCary GrantCinematographyOtto HellerEdited byMerrill G. WhiteMusic byWerner BochmannDistributed byUnited ArtistsRelease dates28 July 1936 (UK)27 February 1937Running time80 minutes (UK) 62 minutes (US)CountryUnited KingdomLanguageEnglish The Amazing Quest of Ernest Blis...

 

 

Dalam artikel ini, nama keluarganya adalah Im. NC.ANC.A pada tahun 2018LahirIm So-eun[1]07 Oktober 1996 (umur 27)Osan, Provinsi Gyeonggi, Korea SelatanPekerjaanPenyanyiaktrisKarier musikGenreK-popInstrumenVokalTahun aktif2013–sekarangLabelJPlanetArtis terkaitUni.TSitus webjplanetentertainment.com/nca/ Im SoeunHangul임소은 Hanja任昭垠 Alih AksaraIm SoeunMcCune–ReischauerIm SoŭnNama panggungHangul앤씨아 Alih AksaraAen SsiaMcCune–ReischauerAen Ssia Im Soeun (Hangul: ...

Міхай ХоробрийMihai Viteazul Оригінальний румунський постер до фільмуЖанр історична драмафільм-біографіяРежисер Серджіу НіколаескуПродюсер Gheorghe PîrîudСценарист Титус ПоповичУ головних ролях Амза Пелля, Ion Besoiud, Серджіу Ніколаеску, Іларіон Чобану, Mircea Albulescud, Флорін ...

 

 

هذه المقالة تحتاج للمزيد من الوصلات للمقالات الأخرى للمساعدة في ترابط مقالات الموسوعة. فضلًا ساعد في تحسين هذه المقالة بإضافة وصلات إلى المقالات المتعلقة بها الموجودة في النص الحالي. (أكتوبر 2018) كلية مدراس المسيحية   معلومات التأسيس 1837  الموقع الجغرافي إحداثيات 12°55′1...

 

 

De islam is de op een na grootste wereldreligie met ruim 1,6 miljard aanhangers. Vanaf 610 verspreidde de islam zich over de wereld, beginnende met Mohammed die, volgens de islamitische Hadith een Openbaring van God kreeg. Zie ook het artikel Beknopte chronologie van de islam. Het begin Het Arabisch Schiereiland in pre-islamitische tijden. Door handelscontacten met andere volkeren, zoals de joden, de Byzantijnse en Abessijnse christenen en de Perzische zoroastristen, hadden de Arabieren reeds...

Danish singing duo This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Hot Eyes – news · newspapers · books · scholar · JSTOR (October 2008) (Learn how and when to remove this template message) Hot EyesKirsten Siggaard in Stockholm 2010.Members Kirsten Siggard Søren Bundgaard Hot Eyes was the name adopted for international acts ...

 

 

Final match of Euro 2004 Football matchUEFA Euro 2004 FinalThe Greece team celebrating their winEventUEFA Euro 2004 Portugal Greece 0 1 Date4 July 2004 (2004-07-04)VenueEstádio da Luz, LisbonMan of the MatchTheodoros Zagorakis (Greece)RefereeMarkus Merk (Germany)Attendance62,865WeatherSunny28 °C (82 °F)37% humidity← 2000 2008 → The UEFA Euro 2004 Final was the final match of Euro 2004, the 12th European Championship, a football competition organised by ...

 

 

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Bone-Bone, Luwu Utara – berita · surat kabar · buku · cendekiawan · JSTOR Bone-BoneKecamatanNegara IndonesiaProvinsiSulawesi SelatanKabupatenLuwu UtaraPemerintahan • CamatSyahruddin, S.S...

Para el nuevo Código que reemplazó al que se refiere este artículo, a partir del 1 de agosto del 2015, véase Código Civil y Comercial de la Nación (Argentina). Código Civil de la República Argentina Portada del Código Civil de la República de Argentina. Edición de 1923.Tipo Código civilIdioma EspañolRedactor(es) Dalmacio Vélez SarsfieldPromulgación 29 de septiembre de 1869En vigor 1 de enero de 1871Derogación 1 de agosto de 2015Reemplazado por Código Civil y Comercial de...

 

 

نيكلاس مويساندر معلومات شخصية الميلاد 29 سبتمبر 1985 (العمر 38 سنة)[1]توركو الطول 1.83 م (6 قدم 0 بوصة) مركز اللعب مدافع الجنسية فنلندا  معلومات النادي النادي الحالي مالمو الرقم 4 مسيرة الشباب سنوات فريق 1996–2002 توركو المسيرة الاحترافية1 سنوات فريق م. (هـ.) 2002–2003 توركو 17 ...

 

 

Hotel ContinentalKhách sạn Continental Vista del HotelLocalizaciónPaís  VietnamLocalidad Ciudad Ho Chi MinhCoordenadas 10°46′37″N 106°42′09″E / 10.77694444, 106.7025Mapa de localización Localización del Hotel Ubicación del Hotel[editar datos en Wikidata] El Hotel Continental [1]​ (en vietnamita: Khách sạn Continental) es un hotel en la ciudad Ho Chi Minh, en el sur de Vietnam. Fue llamado así por el Hôtel Continental en París, y se ...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: European Movement Ireland – news · newspapers · books · scholar · JSTOR (September 2017) (Learn how and when to remove this template message) European Movement IrelandEuropean Movement Ireland LogoFormation11 January 1954TypeNot-for-ProfitLegal statusCompany Li...

 

 

One of the three colleges of the University of Edinburgh University of Edinburgh, College of Science and EngineeringEstablished1583Vice-Principal and Head of CollegeProf Dave RobertsonAcademic staff1362Administrative staff744Students9258Undergraduates6235Postgraduates3023AddressKing's Buildings, West Mains Road, Edinburgh, EH9 3JY, United Kingdom, Edinburgh, Scotland55°55′22″N 3°10′30″W / 55.922778°N 3.175°W / 55.922778; -3.175CampusKing's Buildings Central...

 

 

County in Sichuan, People's Republic of ChinaRenshou County 仁寿县CountyLocation of Renshou County (red) within Meishan City (yellow) and SichuanCoordinates: 29°59′44″N 104°08′03″E / 29.9956°N 104.1341°E / 29.9956; 104.1341CountryPeople's Republic of ChinaProvinceSichuanPrefecture-level cityMeishanArea • Total2,716.86 km2 (1,048.99 sq mi)Population • Total1,540,000 • Density570/km2 (1,500/sq mi)Time...

Questa voce o sezione sull'argomento scrittori statunitensi non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. Segui i suggerimenti del progetto di riferimento. Rick Moody Rick Moody, pseudonimo di Hiram Frederick Moody III (New York, 18 ottobre 1961), è uno scrittore statunitense conosciuto per i romanzi La tempesta di ghiaccio, cronaca della dissoluzione ...

 

 

Vicente Fidel López Ministro de Hacienda de la Nación Argentina 7 de agosto de 1890-22 de octubre de 1891Presidente Carlos PellegriniPredecesor Juan Agustín GarcíaSucesor Emilio Hansen Diputado de la Nación Argentinapor Provincia de Buenos Aires 30 de abril de 1876-30 de abril de 1880 9.º Gran Maestre de la Gran Logia de Libres y Aceptados Masones 1879-1880Predecesor Agustín P. JustoSucesor Dos sucesivos: Manuel Hermenegildo Langenheim (1880) Domingo Faustino Sarmiento (1882) Rector de...

 

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!