Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Parametric polymorphism

From Wikipedia, the free encyclopedia
Basis of generic programming
Polymorphism
Ad hoc polymorphism
Parametric polymorphism
Subtyping

Inprogramming languages andtype 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 polymorphicfunctions anddata types are sometimes calledgeneric functions andgeneric datatypes, respectively, and they form the basis ofgeneric programming.

Parametric polymorphism may be contrasted withad hoc polymorphism. Parametrically polymorphic definitions areuniform: 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.

The usual theoretical device for studying parametric polymorphism issystem F, which extendssimply typed lambda calculus withquantification over types.

Basic definition

[edit]

It is possible to write functions that do not depend on the types of their arguments. For example, theidentity functionid(x)=x{\displaystyle {\mathsf {id}}(x)=x} simply returns its argument unmodified. This naturally gives rise to a family of potential types, such asIntInt{\displaystyle {\mathsf {Int}}\to {\mathsf {Int}}},BoolBool{\displaystyle {\mathsf {Bool}}\to {\mathsf {Bool}}},StringString{\displaystyle {\mathsf {String}}\to {\mathsf {String}}}, and so on. Parametric polymorphism allowsid{\displaystyle {\mathsf {id}}} to be given a single,most general type by introducing auniversally quantifiedtype variable:

id:α.αα{\displaystyle {\mathsf {id}}:\forall \alpha .\alpha \to \alpha }

The polymorphic definition can then beinstantiated by substituting any concrete type forα{\displaystyle \alpha }, 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, anappend{\displaystyle {\mathsf {append}}} function thatconcatenates twolists does not inspect the elements of the list, only the list structure itself. Therefore,append{\displaystyle {\mathsf {append}}} can be given a similar family of types, such as[Int]×[Int][Int]{\displaystyle [{\mathsf {Int}}]\times [{\mathsf {Int}}]\to [{\mathsf {Int}}]},[Bool]×[Bool][Bool]{\displaystyle [{\mathsf {Bool}}]\times [{\mathsf {Bool}}]\to [{\mathsf {Bool}}]}, and so on, where[T]{\displaystyle [T]} denotes a list of elements of typeT{\displaystyle T}. The most general type is therefore

append:α.[α]×[α][α]{\displaystyle {\mathsf {append}}:\forall \alpha .[\alpha ]\times [\alpha ]\to [\alpha ]}

which can be instantiated to any type in the family.

Parametrically polymorphic functions likeid{\displaystyle {\mathsf {id}}} andappend{\displaystyle {\mathsf {append}}} are said to beparameterized over an arbitrary typeα{\displaystyle \alpha }.[4] Bothid{\displaystyle {\mathsf {id}}} andappend{\displaystyle {\mathsf {append}}} are parameterized over a single type, but functions may be parameterized over arbitrarily many types. For example, thefst{\displaystyle {\mathsf {fst}}} andsnd{\displaystyle {\mathsf {snd}}} functions that return the first and second elements of apair, respectively, can be given the following types:

fst:α.β.α×βαsnd:α.β.α×ββ{\displaystyle {\begin{aligned}{\mathsf {fst}}&:\forall \alpha .\forall \beta .\alpha \times \beta \to \alpha \\{\mathsf {snd}}&:\forall \alpha .\forall \beta .\alpha \times \beta \to \beta \end{aligned}}}

In the expressionfst((3,true)){\displaystyle {\mathsf {fst}}((3,{\mathsf {true}}))},α{\displaystyle \alpha } is instantiated toInt{\displaystyle {\mathsf {Int}}} andβ{\displaystyle \beta } is instantiated toBool{\displaystyle {\mathsf {Bool}}} in the call tofst{\displaystyle {\mathsf {fst}}}, so the type of the overall expression isInt{\displaystyle {\mathsf {Int}}}.

Thesyntax used to introduce parametric polymorphism varies significantly between programming languages. For example, in some programming languages, such asHaskell, theα{\displaystyle \forall \alpha }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'scall sites.

History

[edit]

Parametric polymorphism was first introduced to programming languages inML in 1975.[6] Today it exists inStandard ML,OCaml,F#,Ada,Haskell,Mercury,Visual Prolog,Scala,Julia,Python,TypeScript,C++ and others.Java,C#,Visual Basic .NET andDelphi 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 isC++template specialization.

In the 1980s, Leivant introduced a stratified (i.e. predicative) version of Girard and Reynold'ssystem F. Leivant's approach is based on a notion of rank of the quantifiers, which measures their nesting depth inside functionconstructors.[7] The ML approach is limited to rank-1 polymorphism in this perspective. Haskell has adopted higher-rank parametric polymorphism in the 1990s. For example, rank-2 parametric polymorphism is used in Haskell to define therunSTmonad, which effectively simulates atype and effect system,[8] with "isolated regions of imperative programming". At type level, state isolation essentially stems from the deeper, rank-2 quantification over state inrunST. (This is not enough to formally describe the runtime semantics ofrunST. For the latter, one needs some additional ingredients likeseparation logic.[9])

Predicativity, impredicativity, and higher-rank polymorphism

[edit]

A type is said to be of rankk (for some fixed integerk) if no path from its root to a{\displaystyle \forall } quantifier passes to the left ofk 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 tok. For example, a type system that supports rank-2 polymorphism would allow(α.αα)T{\displaystyle (\forall \alpha .\alpha \rightarrow \alpha )\rightarrow T} but not((α.αα)T)T{\displaystyle ((\forall \alpha .\alpha \rightarrow \alpha )\rightarrow T)\rightarrow T}. A type system that admits types of arbitrary rank is said to be "rank-n polymorphic".

(This notion of rank is a different from howquantifier rank is defined in classical logic because here it measures nesting depth relative to a non-quantifierconnective, whereas in classical logic non-quantifier connectives do not increase the rank of quantifiers nested under them, but other quantifiers do.)

Rank-1 (predicative) polymorphism

[edit]
icon
This sectionneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources in this section. Unsourced material may be challenged and removed.(February 2019) (Learn how and when to remove this message)

In apredicative type system (also known as aprenex polymorphic system), type variables may not be instantiated with polymorphic types.[1]: 359–360  Predicative type theories includeMartin-Löf type theory andNuprl. 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 astype schemas to distinguish them from ordinary (monomorphic) types, which are sometimes calledmonotypes.

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 theappend{\displaystyle {\mathsf {append}}} function described above, which has the following type:

append:α.[α]×[α][α]{\displaystyle {\mathsf {append}}:\forall \alpha .[\alpha ]\times [\alpha ]\to [\alpha ]}

In order to apply this function to a pair of lists, a concrete typeT{\displaystyle T} must be substituted for the variableα{\displaystyle \alpha } such that the resulting function type is consistent with the types of the arguments. In animpredicative system,T{\displaystyle T} may be any type whatsoever, including a type that is itself polymorphic; thusappend{\displaystyle {\mathsf {append}}} can be applied to pairs of lists with elements of any type—even to lists of polymorphic functions such asappend{\displaystyle {\mathsf {append}}} itself.Polymorphism in the language ML is predicative.[10] This is because predicativity, together with other restrictions, makes thetype system simple enough that fulltype inference is always possible.

As a practical example,OCaml (a descendant or dialect ofML) 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

[edit]

Some type systems support an impredicative function type constructor even though other type constructors remain predicative. For example, the type(α.αα)T{\displaystyle (\forall \alpha .\alpha \rightarrow \alpha )\rightarrow T} is permitted in a system that supports higher-rank polymorphism, even though[α.αα]{\displaystyle [\forall \alpha .\alpha \rightarrow \alpha ]} may not be.[11]

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

Impredicative polymorphism

[edit]

Impredicative polymorphism (also calledfirst-class polymorphism) is the most powerful form of parametric polymorphism.[1]: 340  Informal logic, a definition is said to beimpredicative 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 isSystem F, which allows instantiatingα.αα{\displaystyle \forall \alpha .\alpha \to \alpha } at any type, including itself.

Intype theory, the most frequently studied impredicativetyped λ-calculi are based on those of thelambda cube, especially System F.

Generalizations of the notion of rank

[edit]

Leivant's notion of rank can be generalized to symbols other than quantifiers with a simple, suitable substitution. For example, it can be applied to the (constructor of)intersection types. However, the rank-based type hierarchy that results can have different properties. For instance, type inference for rank-3 and above system F remains undecidable (as detailed above), however, for intersection types, type inference is decidable for all finite ranks.[13]

Bounded parametric polymorphism

[edit]
Main article:Bounded quantification

In 1985,Luca Cardelli andPeter Wegner recognized the advantages of allowingbounds on the type parameters.[14] 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. InStandard 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. InHaskell, bounding is achieved by requiring types to belong to atype class; thus the same function has the typeEqαα[α]Bool{\textstyle \mathrm {Eq} \,\alpha \,\Rightarrow \alpha \,\rightarrow \left[\alpha \right]\rightarrow \mathrm {Bool} } in Haskell. In most object-oriented programming languages that support parametric polymorphism, parameters can be constrained to besubtypes of a given type (see the articlesSubtype polymorphism andGeneric programming).

See also

[edit]

Notes

[edit]
  1. ^abcdefBenjamin 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. Retrieved1 October 2022.
  4. ^Wu, Brandon."Parametric Polymorphism - SML Help".smlhelp.github.io. Archived fromthe original on 1 October 2022. Retrieved1 October 2022.
  5. ^"Haskell 2010 Language Report § 4.1.2 Syntax of Types".www.haskell.org. Retrieved1 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. ^D. Leivant, Polymorphic type inference, in: Conf. Rec. 10th Ann. ACM Symp. Princ. of Prog. Langs., 1983, pp. 88–98.
  8. ^E. Moggi and Amr Sabry. 2001. Monadic Encapsulation of Effects: A Revised Approach (Extended Version). J. Funct.Program. 11, 6 (Nov. 2001), 591-627
  9. ^Amin Timany, Léo Stefanesco, Morten Krogh-Jespersen, Lars Birkedal, "A logical relation for monadic encapsulation of state: proving contextual equivalences in the presence of runST", POPL 2018
  10. ^Mitchell, J. C.; Harper, R. (1988-01-13)."The essence of ML".Proceedings of the 15th ACM SIGPLAN-SIGACT symposium on Principles of programming languages - POPL '88. New York, NY, USA: Association for Computing Machinery. pp. 28–46.doi:10.1145/73560.73563.ISBN 978-0-89791-252-5.
  11. ^Kwang Yul Seo."Kwang's Haskell Blog - Higher rank polymorphism".kseo.github.io. Retrieved30 September 2022.
  12. ^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-SIGACTSymposium on Principles of Programming Languages. Association for Computing Machinery. pp. 161–174.doi:10.1145/292540.292556.ISBN 1581130953.S2CID 14183560.
  13. ^Kfoury, A.J.; Wells, J.B. (January 2004). "Principality and type inference for intersection types using expansion variables".Theoretical Computer Science:1–70.
  14. ^Cardelli & Wegner 1985.

References

[edit]
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=Parametric_polymorphism&oldid=1312165613"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp