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.

Slides:



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

Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
Programming Languages and Paradigms
Programming Languages and Paradigms The C Programming Language.
Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
Chapter TenModern Programming Languages1 Scope. Chapter TenModern Programming Languages2 Reusing Names n Scope is trivial if you have a unique name for.
Scope Chapter Ten Modern Programming Languages.
Scope Chapter TenModern Programming Languages, 2nd ed.1.
Polymorphism Chapter EightModern Programming Languages1.
Chapter EightModern Programming Languages1 Polymorphism.
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
Polymorphism Chapter EightModern Programming Languages1.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
ISBN Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Introduction Two fundamental abstraction facilities.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
C++ fundamentals.
Programming Languages and Paradigms Object-Oriented Programming.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Imperative Programming
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
FALL 2001ICOM Lecture 21 ICOM 4015 Advanced Programming Lecture 2 Procedural Abstraction Reading: LNN Chapter 4, 14 Prof. Bienvenido Velez.
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
Names and Binding In procedural programming, you write instructions the manipulate the “state” of the process where the “state” is the collection of variables.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Bindings and scope  Bindings and environments  Scope and block structure  Declarations Programming Languages 3 © 2012 David A Watt, University.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Chapter EightModern Programming Languages1 Polymorphism.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Basic Semantics Associating meaning with language entities.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Xin Yuan.
Ch. 5 Ch. 51 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (more notes) Dr. Carter Tiernan.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
COMP3190: Principle of Programming Languages
Types in programming languages1 What are types, and why do we need them?
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Ch. 5 Ch. 51 jcmt Summer 2003Programming Languages CSE3302 Programming Languages (more notes) Summer 2003 Dr. Carter Tiernan.
CSC 143F 1 CSC 143 Constructors Revisited. CSC 143F 2 Constructors In C++, the constructor is a special function automatically called when a class instance.
Bernd Fischer RW713: Compiler and Software Language Engineering.
1 Bindings. 2 Outline Preliminaries Scope  Block structure  Visibility Static vs. dynamic binding Declarations and definitions More about blocks The.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
Chapter TenModern Programming Languages1 Scope. Chapter TenModern Programming Languages2 Reusing Names Scope is trivial when all names are unique But.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
ISBN Chapter 12 Support for Object-Oriented Programming.
Advanced Programming in C
Polymorphism (Ch 8) Scope (Ch 10) Who are you? What do you do now?
Type Checking and Type Inference
Names and Attributes Names are a key programming language feature
CS 326 Programming Languages, Concepts and Implementation
Names, Binding, and Scope
Scope, Visibility, and Lifetime
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Semantic Analysis Chapter 6.
Programming Languages and Paradigms
Modern Programming Languages
Types and Related Issues
Presentation transcript:

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 at least a little Scope (Ch 10) n A scope of an identifier (e.g., a variable) is the space where it can be recognized. Where do you live? Where to find you? Who are you? What do you do now?

5/15/2015IT 3272 Polymorphism Example : int f(char a, char b) { return a==b; } -fun f(a, b) = (a = b); ML: C: Every thing is fixed: val f = fn : ''a * ''a -> bool

5/15/2015IT 3273 Common Examples of Polymorphism n Overloading n Parameter coercion n Parametric polymorphism n Subtype polymorphism n (OOP) (Dynamic binding)

5/15/2015IT 3274 Overloading n An overloaded function or operator is one that has at least two definitions. (some restriction, what is it?) n Most PL’s have overloaded operators n Some also allow the programmer to redefine overloaded operators

5/15/2015IT 3275 Predefined Overloaded Operators Pascal: a := 1 + 2; b := ; c := "hello " + "there"; d := ['a'..'d'] + ['f'] ML: val x = 1 + 2; val y = ;

5/15/2015IT 3276 Defining Overloaded Functions C++ allows a function to be overloaded int square(int x) { return x*x; } double square(double x) { return x*x; }

5/15/2015IT 3277 Adding new definitions to Overloaded Operators C++ allows operators to be overloaded. 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; … }

5/15/2015IT 3278 Implementing Overloading n Compilers usually implement overloading straightforwardly: – Give a different name to each definition

5/15/2015IT 3279 Coercion n A coercion is an automatic and implicit type conversion double x; x = (double) 2; double x; x = 2; Explicit type conversion in Java: Coercion in Java:

5/15/2015IT void f(double x) { … } f((byte) 1); f((short) 2); f('a'); f(3); This f can be called with any type of parameter, as long as Java is willing to coerce to type double Parameter Coercion

5/15/2015IT Defining Type Coercions n Some old 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 They wanted to make PLs smart We wanted make PLs precise Must be defined precisely in details about which coercions are performed

5/15/2015IT Where is my penny? double payment, price, change; int i; cout << "Input two real numbers for payment and price: "; cin >> payment >> price; cout << "Payment = " << payment << ", Price = " << price << endl; change = payment-price ; cout << "Change = " << change << endl; cout << "Change*100 = " << change*100 << "\n\n"; i = (payment-price)*100 ; cout << "(Payment-Price)*100 = " << i << endl; Input two real numbers for payment and price: Payment = 20, Price = 3.99 Change = Change*100 = 1601 (Payment-Price)*100 = 1600 There is a criminal charge in 1970’s Input two real numbers for payment and price: Payment = 100, Price = 3.99 Change = Change*100 = 9601 (Payment-Price)*100 = 9601 (x-y)*100  (x*100)-(y*100) Input two real numbers for payment and price: Payment = 10, Price = 3.99 Change = 6.01 Change*100 = 601 (Payment-Price)*100 = 601

5/15/2015IT Difference between Coercion and Overloading: Overloading : type  definition (types determine which definitions) Coercion: definition  type (definitions determine which types) int square(int x) { return x*x; } double square(double x) { return x*x; } void f(int x, int y) { … } square(0.3) f('a', 'b')

5/15/2015IT Parametric Polymorphism C++ Function Templates template X max(X a, X b) { return a > b ? a : b; } JAVA Generic Classes public interface Queue { boolean offer(T item); T remove(); T poll();..... }

5/15/2015IT Example: ML Functions - fun identity x = x; val identity = fn : 'a -> 'a - fun reverse x = = if null x then nil = else (reverse (tl [(hd x)]; val reverse = fn : 'a list -> 'a list

5/15/2015IT Subtype Polymorphism n Especially object-oriented languages. Vehicle SUV Honda Pilot Object Number Integer Double Base type Derived type Java Any SUV is a Vehicle

5/15/2015IT Static  Dynamic Polymorphism Contemporary emphasis Compiling  Running When to be determined:

5/15/2015IT Scope: the space for a name to be identified n Scope is trivial if you have a unique name for everything: n The same names are used over and over, we in most cases have no problems with that. n How does this work? There are 300M people in the USA

5/15/2015IT Definitions n When there are different variables using the same name, there are different possible bindings (definitions) for those names type names, constant names, function names, etc. n Each occurrence must be bound using one of the definitions. Which one? n There are many different ways to solve this scoping problem (i.e., how to bind)

5/15/2015IT The origin of the scoping problem came from logic  x  y(  x  zP(x,y,z)   x(Q(x,y)   z  t(R(y,z,z)  xS(t,x)))  T(x))  x  y(  a  zP(a,y,z)   b(Q(b,y)   c  t(R(y,c,c)  dS(t,d)))  T(x))  -conversion

5/15/2015IT Scoping with blocks Different ML Blocks The let is just a block: no other purpose A fun definition includes a block: n Multiple alternatives have multiple blocks: n Each rule in a match is a block: fun cube x = x*x*x; fun f (a::b::_) = a+b | f [a] = a | f [] = 0; case x of (a,0) => a | (_,b) => b let val.. in.... end

5/15/2015IT Java Blocks n In Java and other C-like languages: a compound statement using { and } n A compound statement also serves as a block: while (i < 0) { int c = i*i*i; p += c; q += c; i -= step; } for (int i=0;i<0; i++) { int c = i*i*i; p += c; q += c; i -= step; } int c = 4; // can ?

5/15/2015IT Nesting Example let end val n = 1 in end Scope of this definition let val n = 2 in n

5/15/2015IT Labeled Namespaces n ML’s structure… structure Fred = struct val a = 1; fun f x = x + a; end; Fred.f or Fred.a

5/15/2015IT C++ Labeled Namespaces namespace IT { int a=2; int f(...) {...} }..... { using namespace IT;... a f(...).. }..... using IT::f;..... IT::f(...).....

5/15/2015IT Java or C++ Example Month.min and Month.max public class Month { public static int min = 1; public static int max = 12; … }

5/15/2015IT Namespace Refinement n Some information and implementation can (may) be hidden in a namespace. Need for OOP. Origin of OOP: abstract data types reveals an interface hides implementation details…

5/15/2015IT Example: An Abstract Data Type namespace dictionary contains a constant definition for initialSize a type definition for hashTable a function definition for hash a function definition for reallocate a function definition for create a function definition for insert a function definition for search a function definition for delete end namespace Interface definitions should be visible Implementation definitions should be hidden

5/15/2015IT Two Approaches n C++ makes every component in a namespace visible n ML uses a separate construct to define the interface (a signature in ML) n Java combines the two approaches

5/15/2015IT Legitimate but not a good idea - val int = 3; val int = 3 : int - fun f int = int*int; val f = fn : int -> int - f 3; val it = 9 : int int is not reserved in ML but....

5/15/2015IT Primitive Namespaces n ML’s syntax can keep types and expressions separated n There is a separate namespace for types fun f(int:int) = (int:int)*(int:int); These are types in the namespace for types These are variable s in the ordinary namespace

5/15/2015IT Primitive Namespaces n Not explicitly created by the programmers (like primitive types) n They are part of the language definition n Some languages have several separate primitive namespaces

5/15/2015IT When Is Scoping Resolved? n All scoping tools we have seen so far are static, i.e., they are determined at compile time n Some languages postpone the decision until runtime: dynamic scoping

5/15/2015IT Dynamical Scoping n Each function has an environment of definitions n If a name that occurs in a function is not found in its environment, its caller’s environment is searched n And if not found there, the search continues back through the chain of callers n This generates a rather odd scope. Well, not that odd.

5/15/2015IT Classic Dynamic Scope Rule 1. From the point of definition to the end of the function in which the definition is defined, plus 2. the scope of any functions that call the function, (even indirectly)— minus the scopes of any re-definitions of the same name in those called functions The scope of a definition:

5/15/2015IT Static vs. Dynamic n The static rule considers only the regions of program text (context of the program), so it can be applied at compile time n The dynamic considers the runtime events: “functions when they are called…” (timing)

5/15/2015IT Block Scope (Static) With block scope, the reference to inc is bound to the previous definition in the same block. The definition in f ’s caller’s ( h ’s) evironment is inaccessible. fun g x = let val inc = 1; fun f y = y+inc; fun h z = let val inc = 2; in f z end; in h x end; g 5 What is the value of g 5 using ML’s classical block scope rule? = 6

5/15/2015IT Dynamic Scope With dynamic scope, the reference to inc is bound to the definition in the caller’s ( h ’s) environment. g 5 = 7 if ML used dynamic scope fun g x = let val inc = 1; fun f y = y+inc; fun h z = let val inc = 2; in f z end; in h x end; caller

5/15/2015IT Dynamic Scope n Only in a few languages: some dialects of Lisp and APL n Available as an option in Common Lisp n Drawbacks: – Difficult to implement efficiently – Creates large and complicated scopes, since scopes extend into called functions – Choice of variable name in caller can affect behavior of called function

5/15/2015IT Separate Compilation n Scope issues extend to the linker: it needs to connect references to definitions across separate compilations n Special support for this is needed

5/15/2015IT C Approach, Compiler Side n Two different kinds of definitions: – Full definition – Name and type only: a declaration (prototype) If several separate compilations want to use the same integer variable x : – Only one will have the full definition, int x = 3; – All others have the declaration extern int x;

5/15/2015IT C Approach, Linker Side n When the linker runs, it treats a declaration as a reference to a name defined in some other file n It expects to see exactly one full definition of that name n Note that the declaration does not say where to find the definition—it just requires the linker to find it somewhere

5/15/2015IT Older Fortran Approach, Compiler Side Older Fortran dialects used COMMON blocks All separate compilations give the same COMMON declaration: COMMON A,B,C COMMON A,B,C A = B+C/2; COMMON X,A,B B = X - A;

5/15/2015IT Older Fortran Approach, Linker Side The linker allocates just one block of memory for the COMMON variables: n The linker does not use the local names COMMON A,B,C A = B+C/2; COMMON X,A,B B = X - A; A B C X A B

5/15/2015IT Modern Fortran Approach A MODULE can define data in one separate compilation A USE statement can import those definitions into another compilation USE says what module to use, but does not say what the definitions are n Unlike the C approach, the Fortran compiler must at least look at the result of that separate compilation