Chapter EightModern Programming Languages1 Polymorphism.

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Overview of Previous Lesson(s) Over View  Front end analyzes a source program and creates an intermediate representation from which the back end generates.
ISBN Chapter 7 Expressions and Assignment Statements.
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
5/15/2015IT 3271 Polymorphism (Ch 8) n A functions that is not fixed is polymorphic n Applies to a wide variety of language features n Most languages have.
Polymorphism Chapter EightModern Programming Languages1.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Polymorphism Chapter EightModern Programming Languages1.
COEN Expressions and Assignment
Type Checking.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
ISBN Chapter 7 Expressions and Assignment Statements.
1 Chapter 7: Expressions Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation,
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
CS102 Data Types in Java CS 102 Java’s Central Casting.
Honors Compilers An Introduction to Algol-68S Jan 24 th 2002.
Type Checking  Legality checks  Operator determination  Overload resolution.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
ISBN Chapter 7 Expressions and Assignment Statements.
ISBN Lecture 07 Expressions and Assignment Statements.
C++ Training Datascope Lawrence D’Antonio Lecture 5 An Overview of C++: What is Polymorphism? - Overloading.
Expressions, Evaluation and Assignments
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Operator Overloading and Type Conversions
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 1998 by Addison -Wesley Longman, Inc. 1 Chapter 6 Arithmetic Expressions - Their evaluation was one of the motivations for the development.
1-1 University of Hail College of Computer Science and Engineering Department of computer Science and Software Engineering Course: ICS313: Fundamentals.
7-1 Chapter 7: Expressions and Assignment Statements Arithmetic Expressions –the fundamental means of specifying computations in a programming language.
Chapter 7 Expressions and Assignment Statements. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Arithmetic Expressions Arithmetic evaluation.
CS 363 Comparative Programming Languages Expressions and Assignment Statements.
C H A P T E R S E V E N Expressions and Assignment Statements.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter EightModern Programming Languages1 Polymorphism.
CSI 3120, Expressions and assignment, page 1 Expressions and assignment Points for discussion Arithmetic expressions Overloading Logical expressions Assignment.
Arithmetic Expressions
Expressions and Assignment Statements
ISBN Chapter 7 Expressions and Assignment Statements.
Chapter 7 © 1998 by Addison -Wesley Longman, Inc Arithmetic Expressions - Their evaluation was one of the motivations for the development of the.
Chapter 7 Expressions and Assignment Statements. Outline Introduction Arithmetic Expressions Overloaded Operators Type Conversions Assignment Statements.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
ISBN Chapter 7 Expressions and Assignment Statements.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
March 31, ICE 1341 – Programming Languages (Lecture #11) In-Young Ko Programming Languages (ICE 1341) Lecture #11 Programming Languages (ICE 1341)
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
1 CS Programming Languages Class 10 September 26, 2000.
Types John Mitchell CS 242. Type A type is a collection of computable values that share some structural property. uExamples Integers Strings int  bool.
Chapter 7 Expressions and Assignment Statements. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 7 Topics Introduction Arithmetic Expressions.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
7-1/27 Chapter 7 Expressions and Assignment Statements Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean.
Expressions and Assignment Statements
Types Type Errors Static and Dynamic Typing Basic Types NonBasic Types
Expressions and Assignment Statements
Polymorphism (Ch 8) Scope (Ch 10) Who are you? What do you do now?
7.2 Arithmetic Expressions
Principles of programming languages 12: Functional programming
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Arithmetic Expressions
Expressions and Assignment Statements
College of Computer Science and Engineering
Chapter 7 Expressions and Assignment Statements.
PRESENTED BY ADNAN M. UZAIR NOMAN
Modern Programming Languages
Presentation transcript:

Chapter EightModern Programming Languages1 Polymorphism

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

Chapter EightModern Programming Languages3 Polymorphism n Functions with that extra flexibility are called polymorphic n 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 EightModern Programming Languages4 Outline n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n Definitions and classifications

Chapter EightModern Programming Languages5 Overloading n An overloaded function name or operator is one that has at least two definitions, all of different types n Many languages have overloaded operators n Some also allow the programmer to define new overloaded function names and operators

Chapter EightModern Programming Languages6 Predefined Overloaded Operators Pascal: a := 1 + 2; b := ; c := "hello " + "there"; d := ['a'..'d'] + ['f'] ML: val x = 1 + 2; val y = ;

Chapter EightModern Programming Languages7 Adding to Overloaded Operators n 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 EightModern Programming Languages8 Operator Overloading In C++ n 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 EightModern Programming Languages9 Defining Overloaded Functions n 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 EightModern Programming Languages10 To Eliminate Overloading int square(int x) { return x*x; } double square(double x) { return x*x; } void f() { int a = square(3); double b = square(3.0); } You could rename each overloaded definition uniquely… square_i square_d

Chapter EightModern Programming Languages11 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 EightModern Programming Languages12 Implementing Overloading n Compilers usually implement overloading the 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 EightModern Programming Languages13 Example: C++ Implementation int shazam(int a, int b) {return a+b;} double shazam(double a, double b) {return a+b;} shazam__Fii: lda $30,-32($30).frame $15,32,$26,0 … shazam__Fdd: lda $30,-32($30).frame $15,32,$26,0 … C++: Assembler:

Chapter EightModern Programming Languages14 Outline n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n Definitions and classifications

Chapter EightModern Programming Languages15 Coercion n A coercion is an implicit type conversion, supplied automatically even if the programmer leaves it out double x; x = (double) 2; double x; x = 2; Explicit type conversion in Java: Coercion in Java:

Chapter EightModern Programming Languages16 Parameter Coercion n Languages support different coercions in different contexts: assignments, other binary operations, unary operations, parameters… n 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 EightModern Programming Languages17 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 EightModern Programming Languages18 Defining Coercions n Language definitions often take many pages to define exactly which coercions are performed n Some languages, especially some older languages like Algol 68 and PL/I, have very extensive powers of coercion n Some, like ML, have none n Most, like Java, are somewhere in the middle

Chapter EightModern Programming Languages19 Example: Java Unary Numeric Promotion 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, or char, unary numeric promotion promotes it to a value of type int by a widening conversion (§5.1.2). Otherwise, a unary numeric operand remains as is and is not converted. Unary numeric promotion is performed on expressions in the following situations: the dimension expression in array creations (§15.9); the index expression in array access expressions (§15.12); operands of the unary operators plus + (§ ) and minus - (§ )... The Java Language Specification James Gosling, Bill Joy, Guy Steele

Chapter EightModern Programming Languages20 Coercion and Overloading: Tricky Interactions n 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 EightModern Programming Languages21 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 EightModern Programming Languages22 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 EightModern Programming Languages23 Outline n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n Definitions and classifications

Chapter EightModern Programming Languages24 Parametric Polymorphism n A function exhibits parametric polymorphism if it has a type that contains one or more type variables n A type with type variables is a polytype n Found in languages including ML, C++ and Ada

Chapter EightModern Programming Languages25 Example: C++ Function Templates template 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 EightModern Programming Languages26 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 [(hd x)]; val reverse = fn : 'a list -> 'a list

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

Chapter EightModern Programming Languages28 Outline n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n Definitions and classifications

Chapter EightModern Programming Languages29 Subtype Polymorphism n A function or operator exhibits subtype polymorphism if one or more of its parameter types have subtypes n Important source of polymorphism in languages with a rich structure of subtypes n Especially object-oriented languages: we’ll see more when we look at Java

Chapter EightModern Programming Languages30 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 EightModern Programming Languages31 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 EightModern Programming Languages32 More Later n We’ll see more about subtype polymorphism when we look at object- oriented languages

Chapter EightModern Programming Languages33 Outline n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n Definitions and classifications

Chapter EightModern Programming Languages34 Polymorphism n We have seen four kinds of polymorphic functions n 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 n No definition covers all these uses, except the basic Greek: many forms n Here are definitions that cover our four…

Chapter EightModern Programming Languages35 Definitions For Our Four n 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 EightModern Programming Languages36 Overloading n Ad hoc polymorphism n Each different type requires a separate definition n Only finitely many in a finite program

Chapter EightModern Programming Languages37 Parameter Coercion n Ad hoc polymorphism n As long as there are only finitely many different types can be coerced to a given parameter type

Chapter EightModern Programming Languages38 Parametric Polymorphism n Universal polymorphism n As long as the universe over which type variables are instantiated is infinite

Chapter EightModern Programming Languages39 Subtype Polymorphism n Universal n As long as there is no limit to the number of different subtypes that can be declared for a given type n True for all class-based object-oriented languages, like Java