Polymorphism. Chapter Eight Modern Programming Languages, 2nd ed. 1

Similar documents
int f(char a, char b) {

Names, Scopes, and Bindings II. Hwansoo Han

Types, Type Inference and Unification

Motivation for typed languages

Lecture 12: Data Types (and Some Leftover ML)

Types. What is a type?

CS558 Programming Languages

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

CS558 Programming Languages

Types and Type Inference

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Types and Type Inference

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Organization of Programming Languages CS3200 / 5200N. Lecture 06

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Fundamentals of Programming Languages

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Lecture #23: Conversion and Type Inference

Chapter 6. Data Types ISBN

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Type Checking. Prof. James L. Frankel Harvard University

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Structuring the Data. Structuring the Data

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Chapter 7. Expressions and Assignment Statements ISBN

COSC252: Programming Languages: Basic Semantics: Data Types. Jeremy Bolton, PhD Asst Teaching Professor

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

CS558 Programming Languages

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

22c:111 Programming Language Concepts. Fall Types I

Polymorphism and Type Inference

Expressions & Assignment Statements

Polymorphism and Type Inference

Type Conversion. and. Statements

Types. Chapter Six Modern Programming Languages, 2nd ed. 1

CSCI312 Principles of Programming Languages!

CSE 431S Type Checking. Washington University Spring 2013

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

CSCI-GA Scripting Languages

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Francesco Nidito. Programmazione Avanzata AA 2007/08

PROGRAMMING IN C++ COURSE CONTENT

Type Systems, Type Inference, and Polymorphism

Chapter 6. Data Types

Expressions and Assignment Statements

CPSC 3740 Programming Languages University of Lethbridge. Data Types

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Chapter 7. Expressions and Assignment Statements

Software II: Principles of Programming Languages. Why Expressions?

1.3b Type Conversion

Haskell 98 in short! CPSC 449 Principles of Programming Languages

Chapter7 Expression and Assignment Statement. Introduction

Data Types The ML Type System

Static Checking and Type Systems

Pierce Ch. 3, 8, 11, 15. Type Systems

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Chapter 6. Data Types ISBN

Binding and Variables

Java TM Introduction. Renaud Florquin Isabelle Leclercq. FloConsult SPRL.

NOTE: Answer ANY FOUR of the following 6 sections:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

G Programming Languages - Fall 2012

Organization of Programming Languages CS320/520N. Lecture 06. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Chapter 7. Expressions and Assignment Statements ISBN

Chapter 7. Expressions and Assignment Statements

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

Operators and Expressions

Programming in C and C++

CSE 230 Intermediate Programming in C and C++

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Chapter 8 :: Composite Types

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Software II: Principles of Programming Languages

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

C - Basics, Bitwise Operator. Zhaoguo Wang

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

301AA - Advanced Programming [AP-2017]

l e t print_name r = p r i n t _ e n d l i n e ( Name : ^ r. name)

Programming in C++ 6. Floating point data types

Outline. 1 About the course

TYPES, VALUES AND DECLARATIONS

Computers Programming Course 6. Iulian Năstac

Properties of an identifier (and the object it represents) may be set at

CSCI 3155: Principles of Programming Languages Exercise sheet #14 28 June 2007

Concepts Introduced in Chapter 6

Programming in Haskell Aug-Nov 2015

Review of the C Programming Language

Introduction to Programming Using Java (98-388)

Programming Languages

Values (a.k.a. data) representation. Advanced Compiler Construction Michel Schinz

Values (a.k.a. data) representation. The problem. Values representation. The problem. Advanced Compiler Construction Michel Schinz

Expressions and Assignment

Transcription:

Polymorphism Chapter Eight Modern Programming Languages, 2nd ed. 1

Introduction Compare these function types The ML function is more flexible, since it can be applied to any pair of the same (equality-testable) type C: int f(char a, char b) { return a==b; ML: - fun f(a, b) = (a = b); val f = fn : ''a * ''a -> bool Chapter Eight Modern Programming Languages, 2nd ed. 2

Polymorphism Functions with that extra flexibility are called polymorphic A difficult word to define: Applies to a wide variety of language features Most languages have at least a little We will examine four major examples, then return to the problem of finding a definition that covers them Chapter Eight Modern Programming Languages, 2nd ed. 3

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter Eight Modern Programming Languages, 2nd ed. 4

Overloading An overloaded function name or operator is one that has at least two definitions, all of different types Many languages have overloaded operators Some also allow the programmer to define new overloaded function names and operators Chapter Eight Modern Programming Languages, 2nd ed. 5

Predefined Overloaded Operators ML: val x = 1 + 2; val y = 1.0 + 2.0; Pascal: a := 1 + 2; b := 1.0 + 2.0; c := "hello " + "there"; d := ['a'..'d'] + ['f'] Chapter Eight Modern Programming Languages, 2nd ed. 6

Adding to Overloaded Operators Some languages, like C++, allow additional meanings to be defined for operators class complex { double rp, ip; // real part, imaginary part public: complex(double r, double i) {rp=r; ip=i; friend complex operator+(complex, complex); friend complex operator*(complex, complex); ; void f(complex a, complex b, complex c) { complex d = a + b * c; Chapter Eight Modern Programming Languages, 2nd ed. 7

Operator Overloading In C++ C++ allows virtually all operators to be overloaded, including: the usual operators (+,-,*,/,%,^,&,,~,!,=,<,>, +=,-=,=,*=,/=,%=,^=,&=, =,<<,>>,>>=,<<=,==,!=,<=,>=,&&,,++,--,- >*,,) dereferencing (*p and p->x) subscripting (a[i]) function call (f(a,b,c)) allocation and deallocation (new and delete) Chapter Eight Modern Programming Languages, 2nd ed. 8

Defining Overloaded Functions Some languages, like C++, permit the programmer to overload function names int square(int x) { return x*x; double square(double x) { return x*x; Chapter Eight Modern Programming Languages, 2nd ed. 9

To Eliminate Overloading int square(int x) { return x*x; square_i double square(double x) { return x*x; void f() { int a = square(3); double b = square(3.0); square_d You could rename each overloaded definition uniquely Chapter Eight Modern Programming Languages, 2nd ed. 10

How To Eliminate Overloading int square_i(int x) { return x*x; double square_d(double x) { return x*x; void f() { int a = square_i(3); double b = square_d(3.0); Then rename each reference properly (depending on the parameter types) Chapter Eight Modern Programming Languages, 2nd ed. 11

Implementing Overloading Compilers usually implement overloading in that same way: Create a set of monomorphic functions, one for each definition Invent a mangled name for each, encoding the type information Have each reference use the appropriate mangled name, depending on the parameter types Chapter Eight Modern Programming Languages, 2nd ed. 12

Example: C++ Implementation C++: int shazam(int a, int b) {return a+b; double shazam(double a, double b) {return a+b; Assembler: shazam Fii: lda $30,-32($30).frame $15,32,$26,0 shazam Fdd: lda $30,-32($30).frame $15,32,$26,0 Chapter Eight Modern Programming Languages, 2nd ed. 13

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter Eight Modern Programming Languages, 2nd ed. 14

Coercion A coercion is an implicit type conversion, supplied automatically even if the programmer leaves it out Explicit type conversion in Java: double x; x = (double) 2; Coercion in Java: double x; x = 2; Chapter Eight Modern Programming Languages, 2nd ed. 15

Parameter Coercion Languages support different coercions in different contexts: assignments, other binary operations, unary operations, parameters When a language supports coercion of parameters on a function call (or of operands when an operator is applied), the resulting function (or operator) is polymorphic Chapter Eight Modern Programming Languages, 2nd ed. 16

Example: Java void f(double x) { f((byte) 1); f((short) 2); f('a'); f(3); f(4l); f(5.6f); This f can be called with any type of parameter Java is willing to coerce to type double Chapter Eight Modern Programming Languages, 2nd ed. 17

Defining Coercions Language definitions often take many pages to define exactly which coercions are performed Some languages, especially some older languages like Algol 68 and PL/I, have very extensive powers of coercion Some, like ML, have none Most, like Java, are somewhere in the middle Chapter Eight Modern Programming Languages, 2nd ed. 18

Example: Java Some operators apply unary numeric promotion to a single operand, which must produce a value of a numeric type: If the operand is of compile-time type Byte, Short, Character, or Integer it is subjected to unboxing conversion. The result is then promoted to a value of type int by a widening conversion or an identity conversion. Otherwise, if the operand is of compile-time type Long, Float, or Double it is subjected to unboxing conversion. Otherwise, if the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int by a widening conversion. Otherwise, a unary numeric operand remains as is and is not converted. In any case, value set conversion is then applied. Unary numeric promotion is performed on expressions in the following situations: Each dimension expression in an array creation expression The index expression in an array access expression The operand of a unary plus operator + The operand of a unary minus operator - The operand of a bitwise complement operator ~ Each operand, separately, of a shift operator >>, >>>, or <<; therefore a long shift distance (right operand) does not promote the value being shifted (left operand) to long The Java Language Specification, Third Edition James Gosling, Bill Joy, Guy Steele, and Gilad Bracha Chapter Eight Modern Programming Languages, 2nd ed. 19

Coercion and Overloading: Tricky Interactions There are potentially tricky interactions between overloading and coercion Overloading uses the types to choose the definition Coercion uses the definition to choose a type conversion Chapter Eight Modern Programming Languages, 2nd ed. 20

Example Suppose that, like C++, a language is willing to coerce char to int or to double Which square gets called for square('a')? int square(int x) { return x*x; double square(double x) { return x*x; Chapter Eight Modern Programming Languages, 2nd ed. 21

Example Suppose that, like C++, a language is willing to coerce char to int Which f gets called for f('a', 'b')? void f(int x, char y) { void f(char x, int y) { Chapter Eight Modern Programming Languages, 2nd ed. 22

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter Eight Modern Programming Languages, 2nd ed. 23

Parametric Polymorphism A function exhibits parametric polymorphism if it has a type that contains one or more type variables A type with type variables is a polytype Found in languages including ML, C++, Ada, and Java Chapter Eight Modern Programming Languages, 2nd ed. 24

Example: C++ Function Templates template<class X> X max(x a, X b) { return a>b? a : b; void g(int a, int b, char c, char d) { int m1 = max(a,b); char m2 = max(c,d); Note that > can be overloaded, so X is not limited to types for which > is predefined. Chapter Eight Modern Programming Languages, 2nd ed. 25

Example: ML Functions - fun identity x = x; val identity = fn : 'a -> 'a - identity 3; val it = 3 : int - identity "hello"; val it = "hello" : string - fun reverse x = = if null x then nil = else (reverse (tl x)) @ [(hd x)]; val reverse = fn : 'a list -> 'a list Chapter Eight Modern Programming Languages, 2nd ed. 26

Implementing Parametric Polymorphism One extreme: many copies Create a set of monomorphic implementations, one for each type parameter the compiler sees May create many similar copies of the code Each one can be optimized for individual types The other extreme: one copy Create one implementation, and use it for all True universal polymorphism: only one copy Can t be optimized for individual types Many variations in between Chapter Eight Modern Programming Languages, 2nd ed. 27

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter Eight Modern Programming Languages, 2nd ed. 28

Subtype Polymorphism A function or operator exhibits subtype polymorphism if one or more of its parameter types have subtypes Important source of polymorphism in languages with a rich structure of subtypes Especially object-oriented languages: we ll see more when we look at Java Chapter Eight Modern Programming Languages, 2nd ed. 29

Example: Pascal type Day = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); Weekday = Mon..Fri; function nextday(d: Day): Day; begin if D=Sun then nextday:=mon else nextday:=d+1 end; procedure p(d: Day; W: Weekday); begin D := nextday(d); D := nextday(w) end; Subtype polymorphism: nextday can be called with a subtype parameter Chapter Eight Modern Programming Languages, 2nd ed. 30

Example: Java class Car { void brake() { class ManualCar extends Car { void clutch() { void g(car z) { z.brake(); void f(car x, ManualCar y) { g(x); g(y); A subtype of Car is ManualCar Function g has an unlimited number of types one for every class we define that is a subtype of Car That s subtype polymorphism Chapter Eight Modern Programming Languages, 2nd ed. 31

More Later We ll see more about subtype polymorphism when we look at objectoriented languages Chapter Eight Modern Programming Languages, 2nd ed. 32

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter Eight Modern Programming Languages, 2nd ed. 33

Polymorphism We have seen four kinds of polymorphic functions There are many other uses of polymorphic: Polymorphic variables, classes, packages, languages Another name for runtime method dispatch: when x.f() may call different methods depending on the runtime class of the object x Used in many other sciences No definition covers all these uses, except the basic Greek: many forms Here are definitions that cover our four Chapter Eight Modern Programming Languages, 2nd ed. 34

Definitions For Our Four A function or operator is polymorphic if it has at least two possible types It exhibits ad hoc polymorphism if it has at least two but only finitely many possible types It exhibits universal polymorphism if it has infinitely many possible types Chapter Eight Modern Programming Languages, 2nd ed. 35

Overloading Ad hoc polymorphism Each different type requires a separate definition Only finitely many in a finite program Chapter Eight Modern Programming Languages, 2nd ed. 36

Parameter Coercion Ad hoc polymorphism As long as there are only finitely many different types can be coerced to a given parameter type Chapter Eight Modern Programming Languages, 2nd ed. 37

Parametric Polymorphism Universal polymorphism As long as the universe over which type variables are instantiated is infinite Chapter Eight Modern Programming Languages, 2nd ed. 38

Subtype Polymorphism Universal As long as there is no limit to the number of different subtypes that can be declared for a given type True for all class-based object-oriented languages, like Java Chapter Eight Modern Programming Languages, 2nd ed. 39