Set-Theoretic Foundation of Parametric Polymorphism and Subtyping

Total Page:16

File Type:pdf, Size:1020Kb

Set-Theoretic Foundation of Parametric Polymorphism and Subtyping Set-theoretic Foundation of Parametric Polymorphism and Subtyping Giuseppe Castagna1 Zhiwu Xu1;2 ∗ 1CNRS, Laboratoire Preuves, Programmes et Systemes,` Univ Paris Diderot, Sorbonne Paris Cite,´ Paris, France. 2State Key Laboratory of Computer Science, Institute of Software, Chinese Academy of Science, Beijing, China Abstract. We define and study parametric polymorphism for a needed, as shown by our practice of Ocsigen [1], a framework to type system with recursive, product, union, intersection, negation, develop dynamic web sites where web-site paths (uri) are associ- and function types. We first recall why the definition of such a sys- ated to functions that take the uri parameters —the so-called “query tem was considered hard—when not impossible—and then present strings”[7]— and return a Xhtml page. The core of the dynamic the main ideas at the basis of our solution. In particular, we intro- part of Ocsigen system is the function register new service duce the notion of “convexity” on which our solution is built up and whose (moral) type is: discuss its connections with parametricity as defined by Reynolds 8X<:Params:(Path × (X ! Xhtml)) ! unit to whose study our work sheds new light. That is, it is a function that registers the association of its two Categories and Subject Descriptors D.3.3 [Programming Lan- parameters: a path in the site hierarchy and a function that fed with guages]: Language Constructs and Features—Polymorphism; Data a query string that matches the description X (Params being the types and structure; F.3.3 [Logics and Meanings of Programs]: XML type of all possible query strings) returns an Xhtml page. Studies of Program Constructs—type structure Unfortunately, this kind of polymorphism is not available and the General Terms Theory, Languages current implementation of register new service must bypass the type system (of OCaml, OCamlDuce [9], and/or CDuce [2]), Keywords Types, subtyping, polymorphism, parametricity, XML losing all the advantages of static verification. So why despite all this interest and motivations does no satis- 1. Introduction factory solution exist yet? The crux of the problem is that, despite several efforts (eg, [15, 20]), it was not known how to define —and The standard approach to defining subtyping is to define a collec- a fortiori how to decide— the subtyping relation for XML types in tion of syntax-driven subtyping rules that relate types with similar the presence of type variables. Actually, a purely semantic subtyp- syntactic structure. However the presence of logical operators, such ing approach to polymorphism was believed to be impossible. as unions and intersections, makes a syntactic characterization dif- In this paper we focus on this problem and —though, hence- ficult, which is why a semantic approach is used instead: type t is a forth we will seldom mention XML— solve it. The solution — subtype of type s if the set of values denoted by t is a subset of the which is more broadly applicable than just to an XML processing set of values denoted by s. The goal of this study is to extend this setting— is based on some strong intuitions and a lot of technical approach to parametric types. Since such type systems are at the work. We follow this dichotomy for our presentation and organize heart of functional languages manipulating XML data, our study it in two parts: an informal description of the main ideas and in- directly applies to them. Parametric polymorphism has repeatedly tuitions underlying the approach and the formal description of the been requested to and discussed in various working groups of stan- technical development. More precisely, in Section 2 we first ex- dards (eg, RELAX NG [5] and XQuery [6]) since it would bring amine why this problem is deemed unfeasible or unpractical and not only the well-known advantages already demonstrated in ex- simple solutions do not work (x2.1-2.3). Then we present the in- isting functional languages, but also new usages peculiar to XML. tuition underlying our solution (x2.4) and outline, in an informal A typical example is SOAP [21] that provides XML “envelopes” way, the main properties that make the definition of subtyping pos- to wrap generic content. Functions manipulating SOAP envelopes sible (x2.5) as well as the key technical details of the algorithm that are thus working on polymorphically typed objects encapsulated decides it (x2.6). We conclude this first part by giving some ex- in XML structures. Polymorphic higher-order functions are also amples of the subtyping relation (x2.7) and discussing related work (x2.8). In Section 3 we present the key steps of the formal treatment ∗ This author was partially supported by the National Natural Science Foun- to support the claims of Section 2 in particular the soundness and dation of China under Grant No. 61070038 and by a joint training program completeness of the algorithm and the decidability of the subtyp- by CNRS and the Chinese Academy of Science. ing relation. We conclude our presentation with Section 4 where we discuss at length the connections between parametricity and our solution, as well as the new perspectives of research that our work opens. It may seem odd that we focus on a subtyping relation Permission to make digital or hard copies of all or part of this work for personal or without defining any calculus to use it. Defining the polymorphic classroom use is granted without fee provided that copies are not made or distributed subtyping relation and defining a polymorphic calculus are distinct for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute problems (though the latter depends on the former), and there is no to lists, requires prior specific permission and/or a fee. doubt that the former is the very harder one. Once the subtyping ICFP’11, September 19–21, 2011, Tokyo, Japan. relation is defined, it can be immediately applied to simple poly- Copyright c 2011 ACM 978-1-4503-0865-6/11/09. $10.00 morphic calculi (eg, an extension with higher-order functions of the language in [15]) but the definition of calculi that fully exploit the these are the sets of pairs in which it is not true that the first pro- expressiveness of these types and of algorithms that (even partially) jection belongs to t1 and the second does not belong to t2 ). infer type annotations are different and very difficult problems that But here the problemJ K is not circularity but cardinality, sinceJ thisK we leave for future work. would require D to contain P(D2), which is impossible. The solution to both problems is given by the theory of semantic 2. The key ideas subtyping [10], and relies on the observation that in order to use 2.1 Regular types types in a programming language we do not need to know what types are, but just how they are related (by subtyping). In other XML types are essentially regular tree languages: an XML type terms, we do not require the semantic interpretation to map arrow is the set of all XML documents that match the type. As such types into the set in (1), but just to map them into sets that induce they can be encoded by product types (for concatenation), union the same subtyping relation as (1) does. Roughly speaking, this types (for regexp unions) and recursive types (for Kleene’s star). turns out to require that for all s1, s2, t1, t2, the function : satisfies To type higher order functions we need arrow types and we also the property: J K need intersection and negation types since in the presence of arrows they can no longer be encoded. Therefore, studying polymorphism s1!s2 ⊆ t1!t2 () P( s1 × s2 )⊆P( t1 × t2 ) (2) for XML types is equivalent to studying it for the types that are J K J K J K J K J K J K coinductively (for recursion) produced by the following grammar: whatever the sets denoted by s1!s2 and t1!t2 are. Equation (2) above covers only the case in which we compare two single arrow t ::= b j t × t j t ! t j t _ t j t ^ t j :t j 0 j 1 types. But, of course, a similar restriction must be imposed also where b ranges over basic types (eg, Bool, Real, Int, . ), and when comparing arbitrary Boolean combinations of arrows. For- 0 and 1 respectively denote the empty (ie, that contains no value) mally, this can be enforced as follows. Let : be a mapping from J K and top (ie, that contains all values) types. In other terms, types T to P(D), we define a new mapping E : as follows (henceforth J K are nothing but a propositional logic (with standard logical con- we omit the : subscript from E : ): J K J K nectives: ^; _; :) whose atoms are 0, 1, basic, product, and arrow E(0)=? E(1)=D types. We use T to denote the set of all types. E(:t)=D n E(t) E(b)= b In order to preserve the semantics of XML types as sets of doc- J K uments (but also to give programmers a very intuitive interpreta- E(t1 _ t2)=E(t1) [ E(t2) E(t1 × t2)= t1 × t2 J K J K tion of types) it is advisable to interpret a type as the set of all E(t1 ^ t2)=E(t1) \ E(t2) E(t1 ! t2)=P( t1 × t2 ) values that have that type. Accordingly, Int is interpreted as the J K J K Then : and D form a set-theoretic model of types if, besides set that contains the values 0, 1, -1, 2,...; Bool is interpreted J K as the set the contains the values true and false; and so on.
Recommended publications
  • An Extended Theory of Primitive Objects: First Order System Luigi Liquori
    An extended Theory of Primitive Objects: First order system Luigi Liquori To cite this version: Luigi Liquori. An extended Theory of Primitive Objects: First order system. ECOOP, Jun 1997, Jyvaskyla, Finland. pp.146-169, 10.1007/BFb0053378. hal-01154568 HAL Id: hal-01154568 https://hal.inria.fr/hal-01154568 Submitted on 22 May 2015 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. An Extended Theory of Primitive Objects: First Order System Luigi Liquori ? Dip. Informatica, Universit`adi Torino, C.so Svizzera 185, I-10149 Torino, Italy e-mail: [email protected] Abstract. We investigate a first-order extension of the Theory of Prim- itive Objects of [5] that supports method extension in presence of object subsumption. Extension is the ability of modifying the behavior of an ob- ject by adding new methods (and inheriting the existing ones). Object subsumption allows to use objects with a bigger interface in a context expecting another object with a smaller interface. This extended calcu- lus has a sound type system which allows static detection of run-time errors such as message-not-understood, \width" subtyping and a typed equational theory on objects.
    [Show full text]
  • Metaobject Protocols: Why We Want Them and What Else They Can Do
    Metaobject protocols: Why we want them and what else they can do Gregor Kiczales, J.Michael Ashley, Luis Rodriguez, Amin Vahdat, and Daniel G. Bobrow Published in A. Paepcke, editor, Object-Oriented Programming: The CLOS Perspective, pages 101 ¾ 118. The MIT Press, Cambridge, MA, 1993. © Massachusetts Institute of Technology All rights reserved. No part of this book may be reproduced in any form by any electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher. Metaob ject Proto cols WhyWeWant Them and What Else They Can Do App ears in Object OrientedProgramming: The CLOS Perspective c Copyright 1993 MIT Press Gregor Kiczales, J. Michael Ashley, Luis Ro driguez, Amin Vahdat and Daniel G. Bobrow Original ly conceivedasaneat idea that could help solve problems in the design and implementation of CLOS, the metaobject protocol framework now appears to have applicability to a wide range of problems that come up in high-level languages. This chapter sketches this wider potential, by drawing an analogy to ordinary language design, by presenting some early design principles, and by presenting an overview of three new metaobject protcols we have designed that, respectively, control the semantics of Scheme, the compilation of Scheme, and the static paral lelization of Scheme programs. Intro duction The CLOS Metaob ject Proto col MOP was motivated by the tension b etween, what at the time, seemed liketwo con icting desires. The rst was to have a relatively small but p owerful language for doing ob ject-oriented programming in Lisp. The second was to satisfy what seemed to b e a large numb er of user demands, including: compatibility with previous languages, p erformance compara- ble to or b etter than previous implementations and extensibility to allow further exp erimentation with ob ject-oriented concepts see Chapter 2 for examples of directions in which ob ject-oriented techniques might b e pushed.
    [Show full text]
  • On Model Subtyping Cl´Ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´Ez´Equel
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by HAL-Rennes 1 On Model Subtyping Cl´ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´ez´equel To cite this version: Cl´ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´ez´equel.On Model Subtyping. ECMFA - 8th European Conference on Modelling Foundations and Applications, Jul 2012, Kgs. Lyngby, Denmark. 2012. <hal-00695034> HAL Id: hal-00695034 https://hal.inria.fr/hal-00695034 Submitted on 7 May 2012 HAL is a multi-disciplinary open access L'archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destin´eeau d´ep^otet `ala diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publi´esou non, lished or not. The documents may come from ´emanant des ´etablissements d'enseignement et de teaching and research institutions in France or recherche fran¸caisou ´etrangers,des laboratoires abroad, or from public or private research centers. publics ou priv´es. On Model Subtyping Clément Guy1, Benoit Combemale1, Steven Derrien1, Jim R. H. Steel2, and Jean-Marc Jézéquel1 1 University of Rennes1, IRISA/INRIA, France 2 University of Queensland, Australia Abstract. Various approaches have recently been proposed to ease the manipu- lation of models for specific purposes (e.g., automatic model adaptation or reuse of model transformations). Such approaches raise the need for a unified theory that would ease their combination, but would also outline the scope of what can be expected in terms of engineering to put model manipulation into action.
    [Show full text]
  • 250P: Computer Systems Architecture Lecture 10: Caches
    250P: Computer Systems Architecture Lecture 10: Caches Anton Burtsev April, 2021 The Cache Hierarchy Core L1 L2 L3 Off-chip memory 2 Accessing the Cache Byte address 101000 Offset 8-byte words 8 words: 3 index bits Direct-mapped cache: each address maps to a unique address Sets Data array 3 The Tag Array Byte address 101000 Tag 8-byte words Compare Direct-mapped cache: each address maps to a unique address Tag array Data array 4 Increasing Line Size Byte address A large cache line size smaller tag array, fewer misses because of spatial locality 10100000 32-byte cache Tag Offset line size or block size Tag array Data array 5 Associativity Byte address Set associativity fewer conflicts; wasted power because multiple data and tags are read 10100000 Tag Way-1 Way-2 Tag array Data array Compare 6 Example • 32 KB 4-way set-associative data cache array with 32 byte line sizes • How many sets? • How many index bits, offset bits, tag bits? • How large is the tag array? 7 Types of Cache Misses • Compulsory misses: happens the first time a memory word is accessed – the misses for an infinite cache • Capacity misses: happens because the program touched many other words before re-touching the same word – the misses for a fully-associative cache • Conflict misses: happens because two words map to the same location in the cache – the misses generated while moving from a fully-associative to a direct-mapped cache • Sidenote: can a fully-associative cache have more misses than a direct-mapped cache of the same size? 8 Reducing Miss Rate • Large block
    [Show full text]
  • Chapter 2 Basics of Scanning And
    Chapter 2 Basics of Scanning and Conventional Programming in Java In this chapter, we will introduce you to an initial set of Java features, the equivalent of which you should have seen in your CS-1 class; the separation of problem, representation, algorithm and program – four concepts you have probably seen in your CS-1 class; style rules with which you are probably familiar, and scanning - a general class of problems we see in both computer science and other fields. Each chapter is associated with an animating recorded PowerPoint presentation and a YouTube video created from the presentation. It is meant to be a transcript of the associated presentation that contains little graphics and thus can be read even on a small device. You should refer to the associated material if you feel the need for a different instruction medium. Also associated with each chapter is hyperlinked code examples presented here. References to previously presented code modules are links that can be traversed to remind you of the details. The resources for this chapter are: PowerPoint Presentation YouTube Video Code Examples Algorithms and Representation Four concepts we explicitly or implicitly encounter while programming are problems, representations, algorithms and programs. Programs, of course, are instructions executed by the computer. Problems are what we try to solve when we write programs. Usually we do not go directly from problems to programs. Two intermediate steps are creating algorithms and identifying representations. Algorithms are sequences of steps to solve problems. So are programs. Thus, all programs are algorithms but the reverse is not true.
    [Show full text]
  • BALANCING the Eulisp METAOBJECT PROTOCOL
    LISP AND SYMBOLIC COMPUTATION An International Journal c Kluwer Academic Publishers Manufactured in The Netherlands Balancing the EuLisp Metaob ject Proto col y HARRY BRETTHAUER bretthauergmdde JURGEN KOPP koppgmdde German National Research Center for Computer Science GMD PO Box W Sankt Augustin FRG HARLEY DAVIS davisilogfr ILOG SA avenue Gal lieni Gentil ly France KEITH PLAYFORD kjpmathsbathacuk School of Mathematical Sciences University of Bath Bath BA AY UK Keywords Ob jectoriented Programming Language Design Abstract The challenge for the metaob ject proto col designer is to balance the con icting demands of eciency simplici ty and extensibil ity It is imp ossible to know all desired extensions in advance some of them will require greater functionality while oth ers require greater eciency In addition the proto col itself must b e suciently simple that it can b e fully do cumented and understo o d by those who need to use it This pap er presents the framework of a metaob ject proto col for EuLisp which provides expressiveness by a multileveled proto col and achieves eciency by static semantics for predened metaob jects and mo dularizin g their op erations The EuLisp mo dule system supp orts global optimizations of metaob ject applicati ons The metaob ject system itself is structured into mo dules taking into account the consequences for the compiler It provides introsp ective op erations as well as extension interfaces for various functionaliti es including new inheritance allo cation and slot access semantics While
    [Show full text]
  • Third Party Channels How to Set Them up – Pros and Cons
    Third Party Channels How to Set Them Up – Pros and Cons Steve Milo, Managing Director Vacation Rental Pros, Property Manager Cell: (904) 707.1487 [email protected] Company Summary • Business started in June, 2006 First employee hired in late 2007. • Today Manage 950 properties in North East Florida and South West Florida in resort ocean areas with mostly Saturday arrivals and/or Saturday departures and minimum stays (not urban). • Hub and Spoke Model. Central office is in Ponte Vedra Beach (Accounting, Sales & Marketing). Operations office in St Augustine Beach, Ft. Myers Beach and Orlando (model home). Total company wide - 69 employees (61 full time, 8 part time) • Acquired 3 companies in 2014. The PROS of AirBNB Free to list your properties. 3% fee per booking (they pay cc fee) Customer base is different & sticky – young, urban & foreign. Smaller properties book better than larger properties. Good generator of off-season bookings. Does not require Rate Parity. Can add fees to the rent. All bookings are direct online (no phone calls). You get to review the guest who stayed in your property. The Cons of AirBNB Labor intensive. Time consuming admin. 24 hour response. Not designed for larger property managers. Content & Prices are static (only calendar has data feed). Closed Communication (only through Airbnb). Customers want more hand holding, concierge type service. “Rate Terms” not easy. Only one minimum stay, No minimum age ability. No easy way to add fees (pets, damage waiver, booking fee). Need to add fees into nightly rates. Why Booking.com? Why not Booking.com? Owned by Priceline.
    [Show full text]
  • Abstract Data Types
    Chapter 2 Abstract Data Types The second idea at the core of computer science, along with algorithms, is data. In a modern computer, data consists fundamentally of binary bits, but meaningful data is organized into primitive data types such as integer, real, and boolean and into more complex data structures such as arrays and binary trees. These data types and data structures always come along with associated operations that can be done on the data. For example, the 32-bit int data type is defined both by the fact that a value of type int consists of 32 binary bits but also by the fact that two int values can be added, subtracted, multiplied, compared, and so on. An array is defined both by the fact that it is a sequence of data items of the same basic type, but also by the fact that it is possible to directly access each of the positions in the list based on its numerical index. So the idea of a data type includes a specification of the possible values of that type together with the operations that can be performed on those values. An algorithm is an abstract idea, and a program is an implementation of an algorithm. Similarly, it is useful to be able to work with the abstract idea behind a data type or data structure, without getting bogged down in the implementation details. The abstraction in this case is called an \abstract data type." An abstract data type specifies the values of the type, but not how those values are represented as collections of bits, and it specifies operations on those values in terms of their inputs, outputs, and effects rather than as particular algorithms or program code.
    [Show full text]
  • Design and Implementation of Generics for the .NET Common Language Runtime
    Design and Implementation of Generics for the .NET Common Language Runtime Andrew Kennedy Don Syme Microsoft Research, Cambridge, U.K. fakeÒÒ¸d×ÝÑeg@ÑicÖÓ×ÓfغcÓÑ Abstract cally through an interface definition language, or IDL) that is nec- essary for language interoperation. The Microsoft .NET Common Language Runtime provides a This paper describes the design and implementation of support shared type system, intermediate language and dynamic execution for parametric polymorphism in the CLR. In its initial release, the environment for the implementation and inter-operation of multiple CLR has no support for polymorphism, an omission shared by the source languages. In this paper we extend it with direct support for JVM. Of course, it is always possible to “compile away” polymor- parametric polymorphism (also known as generics), describing the phism by translation, as has been demonstrated in a number of ex- design through examples written in an extended version of the C# tensions to Java [14, 4, 6, 13, 2, 16] that require no change to the programming language, and explaining aspects of implementation JVM, and in compilers for polymorphic languages that target the by reference to a prototype extension to the runtime. JVM or CLR (MLj [3], Haskell, Eiffel, Mercury). However, such Our design is very expressive, supporting parameterized types, systems inevitably suffer drawbacks of some kind, whether through polymorphic static, instance and virtual methods, “F-bounded” source language restrictions (disallowing primitive type instanti- type parameters, instantiation at pointer and value types, polymor- ations to enable a simple erasure-based translation, as in GJ and phic recursion, and exact run-time types.
    [Show full text]
  • POINTER (IN C/C++) What Is a Pointer?
    POINTER (IN C/C++) What is a pointer? Variable in a program is something with a name, the value of which can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within the computer to hold the value of that variable. • The left side is the value in memory. • The right side is the address of that memory Dereferencing: • int bar = *foo_ptr; • *foo_ptr = 42; // set foo to 42 which is also effect bar = 42 • To dereference ted, go to memory address of 1776, the value contain in that is 25 which is what we need. Differences between & and * & is the reference operator and can be read as "address of“ * is the dereference operator and can be read as "value pointed by" A variable referenced with & can be dereferenced with *. • Andy = 25; • Ted = &andy; All expressions below are true: • andy == 25 // true • &andy == 1776 // true • ted == 1776 // true • *ted == 25 // true How to declare pointer? • Type + “*” + name of variable. • Example: int * number; • char * c; • • number or c is a variable is called a pointer variable How to use pointer? • int foo; • int *foo_ptr = &foo; • foo_ptr is declared as a pointer to int. We have initialized it to point to foo. • foo occupies some memory. Its location in memory is called its address. &foo is the address of foo Assignment and pointer: • int *foo_pr = 5; // wrong • int foo = 5; • int *foo_pr = &foo; // correct way Change the pointer to the next memory block: • int foo = 5; • int *foo_pr = &foo; • foo_pr ++; Pointer arithmetics • char *mychar; // sizeof 1 byte • short *myshort; // sizeof 2 bytes • long *mylong; // sizeof 4 byts • mychar++; // increase by 1 byte • myshort++; // increase by 2 bytes • mylong++; // increase by 4 bytes Increase pointer is different from increase the dereference • *P++; // unary operation: go to the address of the pointer then increase its address and return a value • (*P)++; // get the value from the address of p then increase the value by 1 Arrays: • int array[] = {45,46,47}; • we can call the first element in the array by saying: *array or array[0].
    [Show full text]
  • Subtyping Recursive Types
    ACM Transactions on Programming Languages and Systems, 15(4), pp. 575-631, 1993. Subtyping Recursive Types Roberto M. Amadio1 Luca Cardelli CNRS-CRIN, Nancy DEC, Systems Research Center Abstract We investigate the interactions of subtyping and recursive types, in a simply typed λ-calculus. The two fundamental questions here are whether two (recursive) types are in the subtype relation, and whether a term has a type. To address the first question, we relate various definitions of type equivalence and subtyping that are induced by a model, an ordering on infinite trees, an algorithm, and a set of type rules. We show soundness and completeness between the rules, the algorithm, and the tree semantics. We also prove soundness and a restricted form of completeness for the model. To address the second question, we show that to every pair of types in the subtype relation we can associate a term whose denotation is the uniquely determined coercion map between the two types. Moreover, we derive an algorithm that, when given a term with implicit coercions, can infer its least type whenever possible. 1This author's work has been supported in part by Digital Equipment Corporation and in part by the Stanford-CNR Collaboration Project. Page 1 Contents 1. Introduction 1.1 Types 1.2 Subtypes 1.3 Equality of Recursive Types 1.4 Subtyping of Recursive Types 1.5 Algorithm outline 1.6 Formal development 2. A Simply Typed λ-calculus with Recursive Types 2.1 Types 2.2 Terms 2.3 Equations 3. Tree Ordering 3.1 Subtyping Non-recursive Types 3.2 Folding and Unfolding 3.3 Tree Expansion 3.4 Finite Approximations 4.
    [Show full text]
  • Parametric Polymorphism Parametric Polymorphism
    Parametric Polymorphism Parametric Polymorphism • is a way to make a language more expressive, while still maintaining full static type-safety (every Haskell expression has a type, and types are all checked at compile-time; programs with type errors will not even compile) • 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 • such functions and data types are called generic functions and generic datatypes Polymorphism in Haskell • Two kinds of polymorphism in Haskell – parametric and ad hoc (coming later!) • Both kinds involve type variables, standing for arbitrary types. • Easy to spot because they start with lower case letters • Usually we just use one letter on its own, e.g. a, b, c • When we use a polymorphic function we will usually do so at a specific type, called an instance. The process is called instantiation. Identity function Consider the identity function: id x = x Prelude> :t id id :: a -> a It does not do anything with the input other than returning it, therefore it places no constraints on the input's type. Prelude> :t id id :: a -> a Prelude> id 3 3 Prelude> id "hello" "hello" Prelude> id 'c' 'c' Polymorphic datatypes • The identity function is the simplest possible polymorphic function but not very interesting • Most useful polymorphic functions involve polymorphic types • Notation – write the name(s) of the type variable(s) used to the left of the = symbol Maybe data Maybe a = Nothing | Just a • a is the type variable • When we instantiate a to something, e.g.
    [Show full text]