Share to: share facebook share twitter share wa share telegram print page

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.[1]: 340  Parametrically polymorphic functions and data types are sometimes called generic functions and generic datatypes, respectively, and they form the basis of generic programming.

Parametric polymorphism may be contrasted with ad hoc polymorphism. Parametrically polymorphic definitions are uniform: they behave identically regardless of the type they are instantiated at.[1]: 340 [2]: 37  In contrast, ad hoc polymorphic definitions are given a distinct definition for each type. Thus, ad hoc polymorphism can generally only support a limited number of such distinct types, since a separate implementation has to be provided for each type.

Basic definition

It is possible to write functions that do not depend on the types of their arguments. For example, the identity function simply returns its argument unmodified. This naturally gives rise to a family of potential types, such as , , , and so on. Parametric polymorphism allows to be given a single, most general type by introducing a universally quantified type variable:

The polymorphic definition can then be instantiated by substituting any concrete type for , yielding the full family of potential types.[3]

The identity function is a particularly extreme example, but many other functions also benefit from parametric polymorphism. For example, an function that concatenates two lists does not inspect the elements of the list, only the list structure itself. Therefore, can be given a similar family of types, such as , , and so on, where denotes a list of elements of type . The most general type is therefore

which can be instantiated to any type in the family.

Parametrically polymorphic functions like and are said to be parameterized over an arbitrary type .[4] Both and are parameterized over a single type, but functions may be parameterized over arbitrarily many types. For example, the and functions that return the first and second elements of a pair, respectively, can be given the following types:

In the expression , is instantiated to and is instantiated to in the call to , so the type of the overall expression is .

The syntax used to introduce parametric polymorphism varies significantly between programming languages. For example, in some programming languages, such as Haskell, the quantifier is implicit and may be omitted.[5] Other languages require types to be instantiated explicitly at some or all of a parametrically polymorphic function's call sites.

History

Parametric polymorphism was first introduced to programming languages in ML in 1975.[6] Today it exists in Standard ML, OCaml, F#, Ada, Haskell, Mercury, Visual Prolog, Scala, Julia, Python, TypeScript, C++ and others. Java, C#, Visual Basic .NET and Delphi have each introduced "generics" for parametric polymorphism. Some implementations of type polymorphism are superficially similar to parametric polymorphism while also introducing ad hoc aspects. One example is C++ template specialization.

Predicativity, impredicativity, and higher-rank polymorphism

Rank-1 (predicative) polymorphism

In a predicative type system (also known as a prenex polymorphic system), type variables may not be instantiated with polymorphic types.[1]: 359–360  Predicative type theories include Martin-Löf type theory and Nuprl. This is very similar to what is called "ML-style" or "Let-polymorphism" (technically ML's Let-polymorphism has a few other syntactic restrictions). This restriction makes the distinction between polymorphic and non-polymorphic types very important; thus in predicative systems polymorphic types are sometimes referred to as type schemas to distinguish them from ordinary (monomorphic) types, which are sometimes called monotypes.

A consequence of predicativity is that all types can be written in a form that places all quantifiers at the outermost (prenex) position. For example, consider the function described above, which has the following type:

In order to apply this function to a pair of lists, a concrete type must be substituted for the variable such that the resulting function type is consistent with the types of the arguments. In an impredicative system, may be any type whatsoever, including a type that is itself polymorphic; thus can be applied to pairs of lists with elements of any type—even to lists of polymorphic functions such as itself. Polymorphism in the language ML is predicative.[citation needed] This is because predicativity, together with other restrictions, makes the type system simple enough that full type inference is always possible.

As a practical example, OCaml (a descendant or dialect of ML) performs type inference and supports impredicative polymorphism, but in some cases when impredicative polymorphism is used, the system's type inference is incomplete unless some explicit type annotations are provided by the programmer.

Higher-rank polymorphism

Some type systems support an impredicative function type constructor even though other type constructors remain predicative. For example, the type is permitted in a system that supports higher-rank polymorphism, even though may not be.[7]

A type is said to be of rank k (for some fixed integer k) if no path from its root to a quantifier passes to the left of k or more arrows, when the type is drawn as a tree.[1]: 359  A type system is said to support rank-k polymorphism if it admits types with rank less than or equal to k. For example, a type system that supports rank-2 polymorphism would allow but not . A type system that admits types of arbitrary rank is said to be "rank-n polymorphic".

Type inference for rank-2 polymorphism is decidable, but for rank-3 and above, it is not.[8][1]: 359 

Impredicative polymorphism

Impredicative polymorphism (also called first-class polymorphism) is the most powerful form of parametric polymorphism.[1]: 340  In formal logic, a definition is said to be impredicative if it is self-referential; in type theory, it refers to the ability for a type to be in the domain of a quantifier it contains. This allows the instantiation of any type variable with any type, including polymorphic types. An example of a system supporting full impredicativity is System F, which allows instantiating at any type, including itself.

In type theory, the most frequently studied impredicative typed λ-calculi are based on those of the lambda cube, especially System F.

Bounded parametric polymorphism

In 1985, Luca Cardelli and Peter Wegner recognized the advantages of allowing bounds on the type parameters.[9] Many operations require some knowledge of the data types, but can otherwise work parametrically. For example, to check whether an item is included in a list, we need to compare the items for equality. In Standard ML, 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 in Haskell. In most object-oriented programming languages that support parametric polymorphism, parameters can be constrained to be subtypes of a given type (see the articles Subtype polymorphism and Generic programming).

See also

Notes

  1. ^ a b c d e f Benjamin C. Pierce (2002). Types and Programming Languages. MIT Press. ISBN 978-0-262-16209-8.
  2. ^ Strachey, Christopher (1967), Fundamental Concepts in Programming Languages (Lecture notes), Copenhagen: International Summer School in Computer Programming. Republished in: Strachey, Christopher (1 April 2000). "Fundamental Concepts in Programming Languages". Higher-Order and Symbolic Computation. 13 (1): 11–49. doi:10.1023/A:1010000313106. ISSN 1573-0557. S2CID 14124601.
  3. ^ Yorgey, Brent. "More polymorphism and type classes". www.seas.upenn.edu. Retrieved 1 October 2022.
  4. ^ Wu, Brandon. "Parametric Polymorphism - SML Help". smlhelp.github.io. Retrieved 1 October 2022.
  5. ^ "Haskell 2010 Language Report § 4.1.2 Syntax of Types". www.haskell.org. Retrieved 1 October 2022. With one exception (that of the distinguished type variable in a class declaration (Section 4.3.1)), the type variables in a Haskell type expression are all assumed to be universally quantified; there is no explicit syntax for universal quantification.
  6. ^ Milner, R., Morris, L., Newey, M. "A Logic for Computable Functions with reflexive and polymorphic types", Proc. Conference on Proving and Improving Programs, Arc-et-Senans (1975)
  7. ^ Kwang Yul Seo. "Kwang's Haskell Blog - Higher rank polymorphism". kseo.github.io. Retrieved 30 September 2022.
  8. ^ Kfoury, A. J.; Wells, J. B. (1 January 1999). "Principality and decidable type inference for finite-rank intersection types". Proceedings of the 26th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages. Association for Computing Machinery. pp. 161–174. doi:10.1145/292540.292556. ISBN 1581130953. S2CID 14183560.
  9. ^ Cardelli & Wegner 1985.

References

Read other articles:

مياردان  - قرية -  تقسيم إداري البلد إيران  [1] الدولة  إيران المحافظة أذربيجان الشرقية المقاطعة مقاطعة بستان أباد الناحية الناحية المركزية القسم الريفي قسم مهرانرود الجنوبي الريفي إحداثيات 37°48′53″N 46°40′29″E / 37.81472°N 46.67472°E / 37.81472; 46.67472 السكان ا

FebeIl rapimento delle Leucippidi ritratto su un sarcofago romano Nome orig.Φοίβη Caratteristiche immaginarieSessoFemmina Luogo di nascitaMessene ProfessionePrincipessa di Messene Febe (in greco antico: Φοίβη?, Phoibe) è un personaggio della mitologia greca. Fu una principessa di Messene. Genealogia Figlia di Leucippo[1] e di Filodice[1] (figlia di Inaco). Sposò Polluce[2] (uno dei Dioscuri) e divenne madre di Mnesileo[2] (o Mnasinous[3]).…

Orangestrupig skogssångareStatus i världen: Livskraftig (lc)[1] SystematikDomänEukaryoterEukaryotaRikeDjurAnimaliaStamRyggsträngsdjurChordataUnderstamRyggradsdjurVertebrataKlassFåglarAvesOrdningTättingarPasseriformesFamiljSkogssångareParulidaeSläkteSetophagaArtOrangestrupig skogssångareS. fuscaVetenskapligt namn§ Setophaga fuscaAuktor(Müller, 1776)Synonymer Dendroica fuscaHitta fler artiklar om fåglar med Fågelportalen Orangestrupig skogssångare[2] (Setophaga fusca) är en nor…

Kedidi Besar Kedidi Besar (Calidris tenuirostris) di luar musim kawin. dalam musim kawin Status konservasi Rentan (IUCN 3.1) Klasifikasi ilmiah Kerajaan: Animalia Filum: Chordata Kelas: Aves Ordo: Charadriiformes Famili: Scolopacidae Genus: Calidris Spesies: C. tenuirostris Nama binomial Calidris tenuirostrisHorsfield, 1821 Burung kedidi besar adalah salah satu keluarga Scolopacidae. Dan merupakan salah satu jenis yang terbesar dari jenis Calidris lainnya. Deskripsi Badan dan Suara Ber…

Waffle House Inc. Tipo PrivadaIndustria RestaurantesFundación 1955 en Avondale Estates, GeorgiaSede central Condado de Gwinnett, GA,  Estados UnidosProductos Comida rápidaIngresos 1.1 billones de USD (2012)Sitio web wafflehouse.com[editar datos en Wikidata] Waffle House (en español Casa de Gofres) es una cadena de restaurantes de comida rápida estadounidense. Se encuentran en el sur de los Estados Unidos, y en total hay en más de 1700 localidades en 25 estados. La sede de Waf…

أبجدية جاوية ٭ قد تحتوي هذه الصفحة على يونيكود الألفبائية الصوتية الدولية. تعديل مصدري - تعديل   صفحات من حكايات عبد الله بالخط الجاوي (مكتبة سنغافورة الوطنية) الفاء المثلثة تُنطق مثل «البي الثقيلة» الإنجليزية الأبجدية الجاوية (توليسن جاوي، أو ياوي في فطاني) نظام كتابة مشت…

Jalan Pemuda dilihat dari JPO Halte Transjakarta UNJ (2015) Universitas Negeri Jakarta, salah satu bangunan yang terletak di Jalan Pemuda. Jalan Pemuda adalah nama salah satu jalan utama Jakarta. Jalan ini menghubungkan Matraman, Cempaka Putih, Rawamangun dan Pulo Gadung. Jalan ini membentang sepanjang 3,3 KM dari Rawamangun, Pulo Gadung, Jakarta Timur sampai Jatinegara Kaum, Pulo Gadung, Jakarta Timur. Jalan ini melintasi 3 Kelurahan, yakni: Rawamangun, Pulo Gadung, Jakarta Timur Jati, Pulo Gad…

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يناير 2020) تأثير السلور (بالإنجليزية: Catfish effect)‏ هو تأثير منافس قوي في جعل الضعفاء يطورون أنفسهم.[1] الوسائل التي يطبق بها هذا التأثير في منظمة تسمى إدارة السلور.[2]…

Note: this article is one of a set, describing coronations around the world. For general information related to all coronations, please see the umbrella article Coronation. Coronation of Haile Selassie as Negus (king) of Abyssinia in 1928. Coronations in Africa are held, or have been held, in or amongst the following countries, regions and peoples: By country, region or people Ashanti The Asantehene, the ruler of the Ashanti of Ghana begins his reign by being raised and lowered over the Golden S…

English footballer & manager Dave Challinor Challinor training with Bury in 2007Personal informationFull name David Paul Challinor[1]Date of birth (1975-10-02) 2 October 1975 (age 48)[1]Place of birth Chester, England[1]Height 6 ft 1 in (1.85 m)[2]Position(s) Centre-back[1]Team informationCurrent team Stockport County (manager)Senior career*Years Team Apps (Gls)1994–2002 Tranmere Rovers 140 (6)2002–2004 Stockport County 100 (5)2…

Script used for writing the Coptic language 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: Coptic script – news · newspapers · books · scholar · JSTOR (February 2015) (Learn how and when to remove this template message) Coptic scriptScript type Alphabet Time period2nd century A.D.[1] to present (in Cop…

Japanese volleyball team Saitama Ageo MedicsGroundAgeo, Saitama, JapanManagerHead Coach Masahiro Hirukawa Antônio Marcos LerbachCaptainAkane YamagishiLeagueV.League 12022-20234th placeWebsiteClub home page Saitama Ageo Medics (埼玉上尾メディックス Saitama Ageo Medikkusu) is a women's volleyball team based in Ageo city, Saitama, Japan. It plays in V.League 1. The club was founded in 2001. The owner of the team is Ageo Medical Group. History Founded in 2001. Promoted to V.Challenge Leag…

This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Crip Hop – news · newspapers · books · scholar · JSTOR (October 2017)2001 studio album by Jayo FelonyCrip HopStudio album by Jayo FelonyReleasedOctober 23, 2001GenreWest Coast hip hopgangsta rapLength1:03:34LabelAmerican Music CorporationProducer…

VictoriaPutri Mahkota SwediaAdipati Wanita VästergötlandPutri Mahkota Victoria pada tahun 2018Kelahiran14 Juli 1977 (umur 46)Solna, Stockholm, SwediaWangsaBernadotteNama lengkapVictoria Ingrid Alice DésiréeAyahCarl XVI Gustaf dari SwediaIbuSilvia dari SwediaPasanganDaniel Westling (nikah 2010)AnakPutri Estelle, Adipati ÖstergötlandPangeran Oscar, Adipati SkåneAgamaGereja Swedia Keluarga Kerajaan Swedia Baginda Sang RajaBaginda Sang Permaisuri Paduka Sang Putri MahkotaPaduka Adipati d…

Sexual activity that involves inserting a person's body part into another person Penile-vaginal penetration occurring in the missionary position, depicted by Édouard-Henri Avril Sexual penetration is the insertion of a body part or other object into a body orifice, such as the mouth, vagina or anus, as part of human sexual activity or sexual behavior in non-human animals. The term is most commonly used in statute law in the context of proscribing certain sexual activities. Terms such as sexual …

Esta página cita fontes, mas que não cobrem todo o conteúdo. Ajude a inserir referências. Conteúdo não verificável pode ser removido.—Encontre fontes: ABW  • CAPES  • Google (N • L • A) (Outubro de 2020) Modelo do processo DSDM de Desenvolvimento de Software Metodologia de Desenvolvimento de Sistemas Dinâmicos (do inglês Dynamic Systems Development Method - DSDM) é uma metodologia de desenvolvimento de software originalmen…

German footballer This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Bernd Hölzenbein – news · newspapers · books · scholar · JSTOR (September 2008) (Learn how and when to remove this template messag…

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Maret 2016. artikel ini perlu dirapikan agar memenuhi standar Wikipedia. Tidak ada alasan yang diberikan. Silakan kembangkan artikel ini semampu Anda. Merapikan artikel dapat dilakukan dengan wikifikasi atau membagi artikel ke paragraf-paragraf. Jika sudah dirapikan, s…

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: Welcome to Tomorrow – news · newspapers · books · scholar · JSTOR (July 2023) (Learn how and when to remove this template message) 1994 studio album by Snap!Welcome to TomorrowStudio album by Snap!Released30 September 1994Recorded1993–1994Length46:04Labe…

Azizah HanumLahirAzizah Hanum Husin22 Oktober 1989 (umur 34)Jakarta, IndonesiaAlmamaterInstitut Ilmu Sosial dan Ilmu Politik JakartaPekerjaanPresentermusisiaktrisTahun aktif2012—sekarang Azizah Hanum Husin (lahir 22 Oktober 1989) merupakan presenter, musisi, dan aktris berkebangsaan Indonesia.[1] Pendidikan SMA Negeri 35 Jakarta (2005—2007) Jurusan Jurnalistik, Fakultas Komunikasi - Institut Ilmu Sosial dan Ilmu Politik Jakarta (2008—2012)[2] Maastricht School of …

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 3.144.40.204