CS 234319: Programming Languages - Technion · CS 234319: Programming Languages Prof. Joseph...

96
CS 234319: Programming Languages Prof. Joseph (Yossi) Gil 1 Department of Computer Science THE TECHNIONIsrael Institute of Technology Technion City, Haifa 32000, Israel November 2013 1 [email protected]

Transcript of CS 234319: Programming Languages - Technion · CS 234319: Programming Languages Prof. Joseph...

CS 234319: Programming Languages

Prof. Joseph (Yossi) Gil 1

Department of Computer ScienceTHE TECHNION—Israel Institute of Technology

Technion City, Haifa 32000, Israel

November 2013

[email protected]

3.Advanced Typing 3.3. Polymorphism

Where Are We?3. Advanced Typing

3.3. Polymorphism

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--1

3.Advanced Typing 3.3. Polymorphism

What Shall We Learn? Wikipedia Entries17

Ad hoc PolymorphismFunction OverloadingOperator OverloadingParametric Polymorphism

Polymorphism

Type Conversion

Type Punning

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

17Feel free to click on each of these terms to access the appropriate entryJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--2

3.Advanced Typing 3.3. Polymorphism

What’s Monomorphism?18

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Monomorphic = “single-shaped”

In a monomorphic type system, literals / values / variables / parameters /function results / operators/etc., have a unique type.

PASCAL’s type system is largely monomorphic:

Programmer Defined must specify the exact typePre-Defined sometimes have more than one type

18A hand-waving, but good enough explanationJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--3

3.Advanced Typing 3.3. Polymorphism

“More than One Type” ≈ Polymorphism19

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Poly-Morphism = poly + morphos [Greek] = many + form.

literally, the capacity of an entity to have several shapes

19A hand-waving, but good enough explanationJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--4

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.1. Overloading

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--5

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

What’s Overloading?

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Definition (Overloading)An overloaded term is a term that has multiple mean-ings, which may, but also may not be related.

Please wait to hear about other kinds of polymorphism

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--6

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Overloading in Natural Languages

English lie to present false information with the intention ofdeceiving

lie to place oneself at rest in a horizontal positionUnrelated meanings in this example.

Hebrew Shalom peaceShalom Hi!Shalom Goodbye!

Meanings are related (one blesses a comrade with peace uponmeeting and departing)

Arabic Salam is overloaded similarly to “Shalom”.

The Fundamental Rule of OverloadingThe intended meaning is always fig-ured out by context

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--7

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Keyword Overloading in PASCAL

The keyword “of” serves

Sets VAR s: Set of Char;

Records TYPE Student = Record . . . of . . . end;

Multi-branch Conditional Case month of January: . . .

Arrays CONSTN = 100;

TYPERange = 1..N;Matrix = Array[Range] of

array[Range] of Real;

Variant Records TYPEKind = (NIL, CONS, ATOM);CONS_CHILD = Recordcase tag: Kind of . . . end;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--8

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Keyword Overloading in C++

The different meanings of PASCAL’s “of” are quite similar; in contrast,meanings of C++’s “static” keyword are only vaguely similar;

Scope static char buff[1000];// Antonym of extern; global in current compilation// unit20, but inaccessible// from other compilation units.

Storage Class int counter(void) {static int val = 0;// Antonym of auto; value persists between// different invocationsreturn val++;

}

Static Members struct S {static int n; // shared by all instances of struct S;

};20Legalese for “file”

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--9

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Function / Procedure / Operator Overloading

Incidental use of the same keyword for different purposes in the PL’sgrammar is not so interesting. What’s more interesting is the case that thesame identifier (or operator) denotes several distinct entities:

Definition (Function / Procedure / Operator overloading)An identifier or operator is said to be overloaded if it simulta-neously denotes two or more distinct functions or procedures

A mechanism for better utilization of scarce “good” names and symbols.

Actual meaning is determined by context

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--10

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Built in Operator Overloading in PASCAL

Operator “-” in PASCAL serves for

Integer Negation Integer→ Integer

Real Negation Real→ Real

Integer Subtraction Integer× Integer→ Integer

Real Subtraction Real× Real→ Real

Set Difference Set(σ)× Set(σ)→ Set(σ), where σ is any of thetypes for which PASCAL’s sets can be created

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--11

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Built-in Function and Procedure Overloading in PASCAL

Procedures Program Write;Type Days = (Sunday, Monday);BeginWriteln(0);Writeln(0.0);Writeln(false);Writeln(Sunday)

end.

Output is00.000000000E+00FALSESunday

Functions eof, succ, ord apply to many types, but as we shall see later,their polymorphism is not overloading21

21If you are curious, it is called parametric polymorphismJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--12

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Built-in Operator Overloading in C

Many built-in operators offer overloaded semanticsf(int a, int b, double x, double y){a + b; /∗ Integer addition ∗/x + y; /∗ Floating point addition ∗/

}

and more, e.g., operator “*” is used for

Integer Multiplication int× int→ int

Long Integer Multiplication long× long→ long

Floating Point Multiplication double× double→ double

Pointer Dereferencing Pointer(σ)→ σ for any type σ

Observe that “*” has another overloading in type definitions, but thisoverloading is not of the sort of operator overloading.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--13

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Function Overloading in C++

C forbids function overloading, but its young, fat, and ugly sister C++welcomes it:

Function Overloading in C++

double max(double d1, double d2);char max(char c1, char c2);char* max(char* s1, char* s2);const char* max(const char* s1, const char* s2);

Note that neither C, nor C++ have “built-in” functions, so neither of these sisterlanguages could have built-in function overloading.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--14

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Operator Overloading in C++

Overloading operator +=

class Rational {public:Rational(double);const Rational& operator += (const Rational& other);. . .

};

In C++ you can overload even stuff you did not know was an operator

Including “()”, the “function call”operator

Including the “type casting” operator

Including “,”, the comma operator

Including “[]”, the array access operator

Including “*”, the dereferencing operator

Including “->*”, the field access operator

. . .

not so easy to learn and useJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--15

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Overloading in JAVA

Even if you do not know JAVA, you should be able understand and apply thefollowing:

Built-in Operator Overloading: Similar to C++but in addition, “+” serves also for string concatenation.

Programmer Defined Overloading: None.Language designer did not wish to replicate the C++nightmare.

Built-in Function Overloading: None.JAVA just like many other languages has no “built-in”functions.

Programmer Defined Function Overloading: Similar to C++.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--16

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Overloading in ADA

PASCAL does not allow operator overloading, but its young, fat and uglysister, ADA, does, e.g., operator “/” in ADA denotes

Integer Division Integer× Integer→ Integer

Real Division Real× Real→ Real

Programmer defined overloading:function "/" (m, n : Integer) return Float isbegin

return Float(m) / Float(n);end;

Adds another meaning to division of integers: it can now also return a realnumber.The actual meaning is determined by context:

(i) which parameters are passed to operator “/” upon invocation

(ii) how its result is used.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--17

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Ambiguity Resolution with Overloading

Consider the call Id(E) where Id denotes both:

a function f1 of type S1 → T1

a function f2 of type S2 → T2

Context Independent (C++)

Either f1 or f2 is selecteddepending solely on thetype of E

We must have S1 6= S2

May lead to ambiguities inthe presence of coercion

Context Dependent (ADA)

Either f1 or f2 is selected depending on eitheron the type of E or how Id(E) is used.

Either S1 6= S2 or T1 6= T2 (or both).

Ambiguity is not always resolved:x : Float:=(7/2)/(5/2);

Has at least two ambiguous interpretations:

3/2 = 1.5, 3.5/2.5 = 1.4.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--18

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Overloading vs. Hiding

Hiding (by lexical scope): an identifier defined in an inner scope hides anidentifier defined in an outer scope

Example

static long tail;. . .int main(int ac, char **av) {const char **tail = av+ac-1; // hides outer tail. . .

}

Comparison: both do not make polymorphic types

Overloading Multiple meanings co-exist

Hiding New meaning masks the old meaning.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--19

3.Advanced Typing 3.3. Polymorphism / 3.3.1. Overloading

Overloading and Hiding Together?

May be challenging for language designers?

Can inner definition overload external definition?

What happens if an inner definition hides one overloaded outerdefinition, but not the other?

ExerciseProvide examples in concrete languages, andsee how they deal with these dilemmas.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--20

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.2. Coercion

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--21

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

What’s Coercion?

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Definition (Coercion)An implicit mapping from values of one typeto values of another type is called coercion, butalso type conversion and casting.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--22

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Why Coercion?

PASCAL provides coercion from Integer to Real, so we can write:

Primality Testing in PASCAL

Function isPrime(n: integer): Boolean;Var d: Integer; primeSoFar: Boolean;BeginprimeSoFar := n >= 2;d := 2;If primeSoFar and (n > 3) then while d <= sqrt(n) dobeginif n mod d = 0 then primeSoFar := false;d := d + 1;

end;isPrime := primeSoFar;

end;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--23

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Implicit Use of Coercion

Coercion Enhances the Utility of Current Code. . .If primeSoFar and (n > 3) thenwhile d <= sqrt(n) do

begin. . .

1 Function sqrt expects a Real, but thanks to coercion we can pass it anInteger

2 Function sqrt returns a Real, but thanks to coercion we can compareits result with an an Integer

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--24

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Type Coercion in Algol-68

Algol-68 allows the following coercions:

From integer to real

Widening From real to complex number

Dereferencing From reference to a variable to its value

Rowing From any value to a singled value array

and more. . .

Now you can understand why modern languages tend to minimize or eveneliminate coercions altogether.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--25

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Built-in Coercion in C++

int pi = 3.14159; // Built−in coercion from double to intfloat x = ’\0’; // Built−in coercion from char to floatextern double sqrt(float);x = sqrt(pi); // Built−in coercion from int to double and then

// Built−in coercion from double to float

Coercion is sometimes called, especially in C++, type casting and typeconversion, without particular distinction between implicit and explicitapplications.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--26

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Programmer Defined Coercion in C++

Can be done byDefining a (non-explicit22 constructor with a single argumentOverloading the type cast operator

class Rational {public:Rational(double);explicit Rational(const char *s

);operator double(void);. . .

};

Rational r = 2; // Built−in// coercion from int to double and// then programmer−defined coercion// from double to Rationaldouble d = sqrt(r);// Programmer−defined coercion// from Rational to doubleRational h = "half"; // ErrorRational h =

Rational("half"); // OK

22In C++, an explicit constructor, i.e., a constructor whose definition is adorned with theexplicit keyword is a constructor which will not be employed for implicit coercion; it canonly be used if invoked explicitly.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--27

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Ambiguity due to Coercion

Coercions’ graph is not always a treeWhat is the path of coercion from unsigned char to longdouble?

unsigned char→ char→ int→ long→ double→ long double

or maybe,

unsigned char→ unsigned→ unsigned long→ long double

Selecting a different path may lead to slightly different semanticsK&R C, ANSI-C and C++ are all different in this respect.

Coercions’ graph is not always a DAG

Types int, double and float in C, can all be coerced into each other.

Therefore, the language definition must specify exactly the semantics ofe.g., ’a’*35+5.3f

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--28

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

Coercions + Overloading

Strategies for support of mixed type arithmetic, e.g., A + B

Overloading and no coercioninteger + integerreal + integerinteger + realreal + real

Coercion and no overloadingreal + realinteger→ real

Coercion and overloadinginteger + integerreal + real,integer→ real

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--29

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

No Mixed Type Arithmetic in ML

- 1+1;val it = 2 : int- 1.0+1.0;val it = 2.0 : real- 1+1.0;stdIn:7.1-7.6 Error: operator and operand

don’t agree [literal]operator domain: int * intoperand: int * realin expression:

1 + 1.0-

No implicit coercion from int to real; must use function real- real;val it = fn : int -> real- (real 1) + 1.0;val it = 2.0 : real-

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--30

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

The Overloading Tournament in C++

In every function call site f(a1,a2, ..., an), there could be manyapplicable overloaded versions of f. C++ applies context independent,compile-time tournament to select the most appropriate overload.

Ranking of Coercions (short version)None or Unavoidable array→ pointer, T → const T , . . .

Size Promotion short→ int, int→ long, float→ double, . . .

Standard Conversion int→ double, double→ int, Derived*→ Base*,

Programmer Defined by constructor or operator overloading

Ellipsis e.g., int printf(const char *fmt, ...)

Winner must be:

Better match in at least one argument

At least as good for every other argument

An error message if no single winner is found

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--31

3.Advanced Typing 3.3. Polymorphism / 3.3.2. Coercion

A Tournament Example

Resolve ambiguity in max(a,b)

Given

double max(double, double);Rational max(long double, Rational);float a;Rational b;

double, double

1st Argument float→ double2nd Argument Rational→ double

long double, Rational

1st Argument float→ long double2nd Argument none

First Argument equally good (size promotion)

Second Argument second contestant wins (“none” is better than “programmerdefined”)

second contestant wins.J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--32

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.3. Universal Polymorphism

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--33

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

What is Universal Polymorphism?

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

The opposite of ad hoc All we have seen so far is ad hoc polymorphism, inwhich the different shapes are manually created.

Each overloaded version is created by hand (programmer / languagedesigner).

Each coercion is created by hand (programmer / language designer).

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--34

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Ad Hoc vs. Universal Polymorphism

Definition: ad hocad hoc adv. 1. For the specific purpose, case, or situation at handand for no other: a committee formed ad hoc to address the issue ofsalaries. –ad hoc adj. 1. Formed for or concerned with one specificpurpose: an ad hoc compensation committee. 2. Improvised andoften impromptu: “On an ad hoc basis, Congress has . . . placed. . . ceilings on military aid to specific countries” (New York Times).[Latin ad, to + hoc, this.]

UNIVERSAL AD HOC

NO. SHAPES Unbounded Finite and Few (often very few)SHAPE GENERATION Automatic ManualSHAPE UNIFORMITY Systematic Coincidental

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--35

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Universal Polymorphism in the Tree of Varieties ofPolymorphism

Just a quick review of the terms used already and to be used later on

Ad Hoc Created by hand; caters for a limited number of types

Overloading A single identifier denotes several functions is an ad hoc termsimultaneously

Reuse is limited to names, but there are is reusable codeCoercion A single function can serve several types thanks to implicit

coercions between typesExtending the utility of a single function, using implicitconversions

Universal Systematic, applies to many types

Parametric Functions that operate uniformly on values of different typesInclusion Subtypes inherit functions from their supertypes

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--36

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Annoying Example: a Monomorphic PASCAL Function

Determine Whether Two Sets of Characters are Disjoint

Type CharSet = set of Char;Function disjoint(s1, s2: CharSet): Boolean;Begin

disjoint := (s1 * s2 = [])end

Type is

℘(Char)× ℘(Char)→ Boolean

Applicable only to sets of Chars.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--37

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Using the Disjoint Monomorphic Function

Applicable to a pair of arguments, each of type ℘Char:VAR chars : CharSet;Begin

. . .If disjoint(chars,[’a’,’e’,’i’,’o’,’u’]) then . . .;

end

But, cannot be applied to arguments of other type, such as, ℘Integer,℘Color, . . .

Counter Example: A PASCAL PolymorphicOperator

The * operator in PASCAL is polymorphic. It can beapplied to any two sets of the same kind of elements

Polymorphism is universal, since the operator works in the same fashionfor all types for which it is applicable.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--38

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

write vs. eof in PASCAL

write(E)Effect depends on the type of E:type Char, type String, typeInteger,. . .

The identifier writesimultaneously denotes severaldistinct procedures, each having itsown type

Overloading

(We ignore in this course the“magic” of Write taking multipleparameters, where each can be of adifferent type.)

eof(F)

Type is: File(σ)→ Boolean,where σ stands for any type

Function is polymorphic(’many-shaped’).

Argument types:File of Char,File of Integer, etc.

operates uniformly on all ofargument types

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--39

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Why Polymorphism? (The Global Picture)

Large software systems tend to use static strongly typed languages, because of

Safety fewer bugs

Efficiency fewer runtime checks, and more efficient use of memory

Clarity typing makes the code clearer

However, typing can be a nuisance (as in function disjoint); the utility ofa given piece of a code may be very restricted by typing.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--40

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Yet Another Annoying PASCAL Example

Procedure sort(var a: Array[1..300] of T);

could not be applied to

Arrays of real Body and declaration has to be repeated with T=Real.

array[1..299] of T Array is too small.

array[1..500] of T Array is too large.

array[0..299] of T Mismatch in indices.

array[1..300] of T No name equivalence!!!!

PASCAL is so fussy and inflexible in its type system that even two identicaltype declarations are considered distinct. A type declaration made at a certainpoint in a program is equivalent only to itself.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--41

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Flexibility of Type System

Flexible23 type system makes typing an aide, not a hurdle

Avoid issuing type error messages on programs which will not make runtime type errors.

Promotes code reuse for many different types.

Clearly, PASCAL offers a very inflexibility type system.

The Holy Grail of Language DesignSimultaneously maintain:

1 Flexibility2 Safety3 Simplicity

23Flexibility is yet another criterion for the classification of type systemsJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--42

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Life Without Handcuffs Can be Wonderful!

In dynamically typed Languages, polymorphic code may be invoked withvariables of different type (writing almost at a pseudo-code level)search(k) {// k is the key to search for

. . .// p is the current position in the search for kfor (p = first(); not exhausted(p,k); p = next(p,k))if (found(p,k))return true;

return false;}

Very flexible, but not so safeAn urban legend tells of an Adrienne rocket failure be-cause an actual parameter in inches was used in a pro-cedure with a formal parameter in centimeters.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--43

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Responses to Inflexibility

1 The C Camp. Weak typing.int qsort(char *base, int n, int width, int(*cmp)())

2 Dynamically Typed Languages Camp. SMALLTALK, PYTHON, etc.:dynamic typing overcomes complex inflexibility problems. In a sense,all code is polymorphic.

3 ADA/C++/ JAVA Camp. Polymorphic type systemsgenerictype T is privatewith function comp(x: T, y: T)procedure sort(a: array(1..max) of T). . .procedure int_sort is new sort(int , "<");. . .

But, what is a “polymorphic type system”?

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--44

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Monomorphic vs. Polymorphic Type Systems

Monomorphic Type SystemsUsed in classical PLs, e.g., PASCAL

Every entity has a single simpletype

Type checking is straightforward

Unsatisfactory for reusablesoftware;

Many standard algorithms areinherently generic (e.g., sort)Many standard data structuresare also generic (e.g., trees)

Polymorphic Type Systems

Appear in modern languages, e.g.,ADA, C++, JAVA and ML.

Entities may have multiple types

Code reuse thanks to universalpolymorphism

Supports

Generic functions, e.g., sort.Generic types, e.g., binarytree.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--45

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

Ad Hoc Polymorphism 6= Polymorphic Type System

Overloading minimal utility. A (small) number of distinct procedures thatjust happen to have the same identifier.

Not a truly polymorphic objectDoes not increase the language’s expressive powerAll connections between shapes is coincidental

Coercion a little greater utilitySame routine can be used for several purposesNumber of purposes is limitedReturn type is always the sameConnection between shapes is determined by the coercions,which are usually external to the routine

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--46

3.Advanced Typing 3.3. Polymorphism / 3.3.3. Universal Polymorphism

The Benefits of Universal Polymorphism

A single function (or type) has a (large) family of related types

The function operates uniformly on its arguments, whatever their type.

Provide a genuine gain in expressive power, since a polymorphicfunction may take arguments of an unlimited variety of types

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--47

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.4. Polymorphic Functions

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--48

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

What are Polymorphic Functions?

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Polymorphic FunctionsFunctions that can work on a variety of types; a kind of parametricpolymorphism i.e., polymorphism occurring for unboundedly many re-lated types. The type variety may or may not show up as an explicitparameter.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--49

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

If PASCAL Allowed Polymorphic Functions. . .

function disjoint(s1, s2: set of σ) :Boolean;begindisjoint := (s1 * s2 = [])

endVAR chars : set of Char;

ints1, ints2 : set of 0..99;. . .if disjoint(chars, [’a’,’e’,’i’,’o’,’u’]) then . . .if disjoint(ints1, ints2) then . . .

Type expressions like σ in the definition of disjoint are called typevariables or type parameters.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--50

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Functions with C++’s Templates

Definitiontemplate<typename24 Type>Type max(Type a, Type b) {return a > b ? a : b;

}

Useint x,y,z;double r,s,t;z = max(x,y);t = max(r,s);

Type ParametersExplicitly declared

Inferred upon use

Can even make this inferenceunsigned long // return type

(*pf) // variable(unsigned long, unsigned long) // argument types= max; // assignment

24typename: a C++ keyword denoting type parameters.J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--51

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Functions in ML

Type variables are used in ML to define parametric polymorphism. However,most times, the variables are implicit.

Definitionfun second(x:σ, y:σ) = y

orfun second(x,y) = y

Type is σ ∗ σ → σ, where σ and σ arearbitrary types.

Use second(13,true)second(name)where name is the pair(1984,"Orwell")

Illegal Use second(13)second(1983,2,23)

Sample ML Session

Standard ML of New Jersey v110.75 [built: Thu May 9 05:41:01 2013]- fun second(x:’s, y:’t) = y;val second = fn : ’a * ’b -> ’b- fun second(x, y) = y;val second = fn : ’a * ’b -> ’b-

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--52

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Identity Function in ML

Identity function σ → σ.fun id(x: σ) = x

represents

Identity mapping on booleans

{false→ false,true→ true}

Identity mapping on integers

{. . . ,−2→ −2,−1→ −1, 0→ 0, 1→ 1, 2→ 2, . . .}

Identity mapping on strings

{ε→ ε,"a"→ "a","b"→ "b", . . . ,"aa"→ "aa","ab"→ "ab", . . . , }

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--53

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Functions taking Function Parameters

Function twice takes as a parameter function f and returns a function gsuch that g(x)=f(f(x)):fun twice(f: σ → σ) = fn (x: σ) => f( f(x) )

e.g.,val fourth = twice(sqr)

Function o takes two arguments, functions f and g and returns a functionwhich is their compositionfun op o (f: β → γ, g: α→ β) = fn (x:α) => f(g(x))

e.g.,val even = not o odd

or,fun twice(f: σ → σ) = f o f

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--54

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Type Inference

The type of an entity is inferred, rather than explicitly stated.

PASCAL Constant definition:CONST pi=3.14159264590;

1 3.14159264590 is of type Real.2 Therefore, pi is of type Real.

ML25 Function definitionfun even(n) = (n mod 2 = 0)

1 mod is of type int× int→ int;2 Since n occurs in n mod 2, n is of type int.3 The type of operator = is σ × σ → bool for all σ;4 n occurs in n mod 2, so n is of type int.5 Therefore, the type of n mod 2 = 0 is bool6 It follows that the type of even is

int→ bool

25ML allows to voluntarily state types of a declared entity. Explicitly stating types, even ifredundant, is usually a good programming practice.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--55

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Type Inference does not Always Produce the Desired Result

Define a max function in ML:

A Max Function in ML

- fun max(x,y) =if x > y then x else y;

val max = fn : int * int -> int

But we want max to operate on reals:

Argument type declaration

- fun max(x:real,y:real) =if x > y then x else y;

val max = fn : real * real -> real

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--56

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Type Inference does not Always Produce the Desired Result

Define a max function in ML:

A Max Function in ML

- fun max(x,y) =if x > y then x else y;

val max = fn : int * int -> int

But we want max to operate on reals:

Since ML does does not allow programmerdefined overloading, we can only have oneversion of function max

Argument type declaration

- fun max(x:real,y:real) =if x > y then x else y;

val max = fn : real * real -> real

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--56

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Type Inference

Type inference might yield a monotype

As for the function even

Type inference might yield a polytypefun id (x) = x

The type of id is σ → σ

fun op o (f, g) = fn (x) => f (g (x))We can see from the way they are used that f and g are functions.The result of g must be the same as the argument type of f.o is of type

(β → γ)× (α→ β)→ (α→ γ)

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--57

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Checking Type Parameters: In C++

Templates arechecked when theyare instantiated, notwhen they aredefined:

A C++ Function and Three Instantiations

1 template <typename T>2 const T& max(const T &a, const T &b) {3 return a > b ? a : b;4 }5 int a = max(2/3,3/2);6 double d = max(2.3,3.2);7 struct S {} s1, s2, s3 = max(s1,s2);

gcc max.Cmax.C: In instantiation of‘const T& max(const T&, const T&) [with T = S]’:

max.C:7:25: required from heremax.C:3:14: error: no match for ‘operator>’(operand types are ‘const S’ and ‘const S’)

return a > b ? a : b;ˆ

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--58

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Checking Type Parameters: In ML

Polymorphic functions are checked when they are defined, not when they areused.

Standard ML of New Jersey v110.75 [built: Thu May 9 05:41:01 2013]- fun max(a:’T, b:’T): ’T = if a > b then a else b;stdIn:1.28-1.50 Error: operator and operand don’t agree [UBOUND match]operator domain: ’Z * ’Zoperand: ’T * ’Tin expression:a > b

-

Cannot define a polymorphic max function, since most types do not have a“greater than” operator, and the language does not offer overloading.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--59

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Polymorphic Functions: C++ vs. ML

ML C++

Declaration of Type Parameters Optional ObligatoryPassing Type Arguments Optional No

Checking On Declaration On Instantiation

Notes:

ML can make a more sophisticated type inference than C++.

In fact, ML can make deductions based on functions return type.

Overloading complicates type inference

For that reason, ML does not allow programmer defined overloading

And, for that reason, ML ignores its own built-in overloading when conductingtype inference.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--60

3.Advanced Typing 3.3. Polymorphism / 3.3.4. Polymorphic Functions

Parametric Polymorphism: ML vs. ADA vs. C++

MLElegant syntax

Type inference

Checking at definitiontime

Implicit instantiation

Limited power, sinceno restrictions on typeparameter26

ADA

Verbose, and readable,but heavy syntax.

No type inference

Checking at definitiontime

Explicit instantiation

Explicit restrictions ontype parameter

C++Ugly, kludge andunreadable syntax

Type inference oninvocation

Checking uponinstantiation

Implicit instantiation27

Implicit restrictions ontype parameter28

26except for equality27of function templates, explicit function template instantiation is possible28Recent versions of C++ allow an explicit list of constraints on type parameters

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--61

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.5. Polytypes

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--62

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

What are Polytypes?

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Poltypes are types which have type parameter, for example, the type ofpolymorphic functions. But, more importantly, generic types, which allowimplementation of data structures such as a generic queue.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--63

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Polytypes

Definitions

Polytype (also called parametric type) atype whose definition contains one ormore type variables

Monotype a type whose definition

includes no type variables;

Monomorphic PL offers solelymonotypes

Polymorphic PL offers also polytypes

Examples: A “plain” polytype, and plenty of types of polymorphic functions:

list(σ)list(σ)→ σ

list(σ)→ Integer

σ → σ

σ × σ → σ

(β → γ)× (α→ β)→ (α→ γ)

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--64

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

A Polytype Derives Many Types

A polytype derives a whole family of types, e.g., type σ → σ derives:

Integer→ Integer,

String→ String,

list(Real)→ list(Real),

. . .

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--65

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

No Programmer-Defined Polytypes in PASCAL!

The type of the pre-defined function eof is File of σ. If PASCAL had userdefined polytypes, we could have written

TYPEPair(σ) = Record

first, second: σ;end;IntPair = Pair(Integer);

RealPair = Pair(Real)list(σ) = . . .;

VARline: list(Char);

Unfortunately, this would not work in PASCAL. All we can write is somethingof the sort ofTYPE IntPair = Record

first, second: Integer;end;

VAR line: CharList;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--66

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Defining Polytypes in ML

type σ pair = σ * σ;datatype σ list = nil | cons of (σ * σ list);fun hd(l: σ list) =

case l of nil => . . . (∗ error ∗)| cons(h,t) => h

and tl(l: σ list) =case l of nil => . . . (∗ error ∗)

| cons(h,t) => tand length(l: σ list) =case l of nil => 0

| cons(h,t) => 1 + length (t)

Notations for some common polytypes:Pair(σ) = σ × σlist(σ) = Unit + (σ × list(σ))Array(σ, σ) = σ → σSet(σ) = ℘(σ)

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--67

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Values of a Polytype

What is the set of values of a polytype? Weird question . . .In C++ A class template has no values, only if you substitute an actual

type to its type variable, you will get a real type.In ML One can easily define values of a poltypes representing

polymorphic functions. For example, the type of the functionsecond is the polytype

σ × σ → σ.

A tough problem—what are the values of the polytype list(σ)?Definition The set of values of any polytype is the intersection of all types

that can be derived from it.Rationale suppose v is a value of a polytype for which no monotype

substitution was performed. Then the only legitimate operationson v would be those available for any monotype derived fromthe polytype.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--68

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Example: Polytype list(σ)

Monotypes Derived From list(σ)list(Integer) all finite lists of integers, including the empty list.

list(Boolean) all finite lists of truth values, including the empty list.

list(String) all finite lists of strings, including the empty list.

. . .

The empty list is the only common elementNonempty lists are values of a specific monotype, determined by components’ type.

The empty list is a value of any monotypes derived from list(σ)The type of the empty list has type list(σ)There are no other values of type list(σ)

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--69

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Example: The Polytype σ → σ

Monotypes derived from σ → σ :

Integer→ Integer includes the integer identity function, the successorfunction, the absolute value function, the squaring function, etc.

String→ String includes the string identity function, the string reversefunction, the space trimming function, etc.

Boolean→ Boolean includes the truth value identity function, the logicalnegation function, etc.

. . .

The identity function is common to all σ → σ types. In fact, this is the only suchcommon value.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--70

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Values of Polytypes (More Examples)

℘(σ) The empty set, []

Pointer(σ) The value nil.

σ × σ → σ Function second

(β → γ)× (α→ β)→ (α→ γ) Function o

(σ → σ)→ (σ → σ) id, twice, thrice, fourth, etc., andeven function fixedpoint (the functionmapping any σ → σ functionto id : σ → σ.

Pair(σ) = σ × σ empty

Array(σ, σ) = σ → σ empty

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--71

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Polytypes and Software Engineering

The polytype of a function is very telling of what it does. It is often easy toguess what a function does, just by considering its polytype. Many polytypeshave only one value, which eliminates the guessing altogether

Easy examples list(σ)→ σlist(σ)→ list(σ)list(σ)→ Integerσ → σσ × σ → σ(β → γ)× (α→ β)→ (α→ γ)

Slightly more difficult list(σ)× list(σ)→ list(σ × σ),(σ → σ)× list(σ)→ List(σ),(σ × σ → σ)→ σ × List(σ)→ σ

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--72

3.Advanced Typing 3.3. Polymorphism / 3.3.5. Polytypes

Algebra of Polytypes

There are software systems that promote reuse by supporting a search forfunctions based on their signatures.

Clearly, the search must be insensitive to application of the commutativelaws to product and choice.

Further, the search should be made insensitive to choice of labels

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--73

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.6. Inclusion Polymorphism

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--74

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Inclusion Polymorphism

Inclusion Polymorphism: The other kind of universal polymorphism.Arising from an inclusion relation between types or sets of values.

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--75

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subtyping

Monomorphism Polymorphism

Ad hoc

Overloading Coercion

Universal

Parametric

Polymorphic Functions Polytypes

Inclusion

Subtyping

Most inclusion polymorphism is due to subtyping, but not always.

Definition (Subtyping: Version I)

Type A is a subtype of the type Bif A ⊂ eqB.

Definition (Subtyping: Version II)

Type A is a subtype of the type B if A ⊂ eqB, if every valueof A can be coerced into a value of B.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--76

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Inclusion Polymorphism

Examples:Built-in:

PASCAL: The Nil value belongs to all pointer types.C: The value 0 is polymorphic. It belongs to all pointer types.C++: The type void * is a super-type of all pointer types.

User defined (not OOP):PASCAL: subranges

TYPE Index = 1..100;

Anything that works on Integer will also work on the newly definedtype Index.

User defined (OOP)A subclass is also a subtype

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--77

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subranges in PASCAL

PASCAL Subrange Definition

type MonthLength = 28..31;

Type MonthLength has four values: 28, 29,30,31.

Values of make a subset of type Integer.

Any operation that expects an Integer value will happily accept avalue of type MonthLength.

Type MonthLength “inherits” all operations of type Integer.

“Inheritance” in PASCAL

A PASCAL subrange type “inherits” all the operations of its parent type;otherwise, no PASCAL type inherits any operations from another distinct type.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--78

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subtypes in PASCAL

PASCAL recognizes only one restricted kind of subtype: subranges of discreteatomic types.

Example

TYPE Natural = 0..maxint;Small = -3..+3;

VAR i: Integer;n: Natural;s: Small;

Safe i:=n and i:=s

Unsafe n:=i, s:=i, n:=s and s:=n (require run-time range check)

A value may belong to several (possibly many) subtypes. Run time check isrequired to verify that a value belongs to a certain subtype.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--79

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subtypes in ADA: Built in Types

In contrast, ADA allows subtypes of all atomic types, as well as user-defined,composite types.

Discrete Types

subtype Natural is Integer range 0..Integer’last;subtype Small is Integer range -3..+3;

Indiscrete Types

subtype Probability is Float range 0.0..1.0;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--80

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subtypes in ADA: Array Types

String Example

type String is array (Integer range <>) of Character;subtype String5 is String (1..5);subtype String7 is String (1..7);

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--81

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Subtypes in ADA: User Defined Types

type Sex is (f, m);type Person (gender : Sex) isrecordname : String (1..8);age : Integer range 0..120;

end record;subtype Female is Person (gender => f);subtype Male is Person (gender => m);

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--82

3.Advanced Typing 3.3. Polymorphism / 3.3.6. Inclusion Polymorphism

Hypothetical ML with Structural Subtyping

Some Geometric Types

type point = {x: real, y: real};type circle = {x: real, y: real, r: real};type box = {x: real, y: real, w: real, d: real};

Assuming inheritance relationship being derived from structure29, we have

box ≺ circle ≺ point.

Operations associated of point should be applicable to box, e,.g.,

move : σ ⊂ eqPoint • σ × Real× Real→ σ.

29Observe that in most mainstream languages, including JAVA and C++, structure is derivedfrom inheritance relationship

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--83

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Where Are We?3. Advanced Typing

3.3. Polymorphism3.3.7. Case Studies / Exercises

1. Introduction

2. Values and Types

3. Advanced Typing3.1 Classification of Type Systems

3.2 Structural vs. Nominal Typing3.3 Polymorphism3.3.1 Overloading3.3.2 Coercion3.3.3 Universal Polymorphism3.3.4 Polymorphic Functions3.3.5 Polytypes3.3.6 Inclusion Polymorphism3.3.7 Case Studies / Exercises

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--84

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Q: Overloading + Coercion + Parametric + Inclusion = ?A: C++ Style Headache!

With the declarations made previously, which version of max would thefollowing invoke?

max(Rational(3),′ \′)

What will be printed?

void f(int) { cout << "int"; }void f(char) { cout << "char"; }void f(char *) { cout << "char *"; }

void g() { f(0); }

Many languages forbid overriding and coercion and severely restrictparametric polymorphism for precisely this reason.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--85

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Case Study: Universal Pointer in C

Universal Pointer Type In C, a void* pointer could be assigned to anypointer, and any pointer can be assigned to void*.extern void* malloc(size_t);extern void free(void*);void f(size_t n) {long *buff = malloc(n * sizeof(long));. . .free(buff);

}

Parametric Polymorphism In C the coercion from long* to void* andvice-versa is not ad-hoc

It universally exists for all pointer typesThe actions performed are the same for allpointer types

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--86

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Case Study: Casting in C++

C++ deprecates C-style casts; instead there are four cast operations

const cast<σ> takes a type σ and returns a cast operator fromany type σ to σ provided only that σ can beobtained from σ just by adding const

reinterpret cast<σ> takes a type σ and returns a cast operator fromany type σ to σ (useful for peeping into bitrepresentations)

static cast<σ> takes a type σ and returns a cast operator fromany type σ, provided this is a standard casting(e.g. double to int)

dynamic cast<σ> takes a type σ of a derived class and returns acast operator from any type σ of its base classesinto σ.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--87

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Const Exercises

Given are the following definitions.typedef char* t1;typedef char* const t2;typedef const char* t3;typedef const char* const t4;

t1 c1;t2 c2;t3 c3;t4 c4;

Determine for all i, j, k which of the following commands will legallycompile?

ci = cj;ci = const cast<tj>(ck);*ci = *cj;*const cast<ti>(cj) = *ck;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--88

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Polytypes in ADA: generics

generic(type ElementType) module Stack;export Push,Pop,Empty,StackType,MaxStackSize;constant MaxStackSize = 10;type private StackType =recordSize: 0..MaxStackSize := 0;Data: array 1..MaxStackSize of ElementType;end;procedure Push(

reference ThisStack: StackType;readonly What: ElementType);

procedure Pop(reference ThisStack):ElementType;

procedure Empty(readonly ThisStack):Boolean;end; −− Stackmodule IntegerStack = Stack(integer);

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--89

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Parametric Polymorphism in PASCAL

The following nonsense code demonstrates PASCAL’s built-in parametric (allenumerated types) polymorphism of control structure (up and down forloops and case), relational operators, and the ord, succ and predfunctions.for m := January to December dofor d := Saturday downto Sunday docase suit ofClub, Heart:suit := succ(suit);

Diamond, Spade:if suit < Heart thenif ord(m) < ord(d) thensuit := pred(suit);

end;

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--90

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Responses to Inflexibility in JAVA

JAVA = C++ minus all “complexities”

Originally dynamic typingComparator.compare(Object, Object)

Now polymorphic typescomparator<T>.compare(T, T)

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--91

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Non-Type Parametric Polymorphism

What we have seen so far is. . .

Entity Type (parametrized)

Parameter Type

Output Type (concrete)

Entity Function (parameterized)

Parameter Type

Output Function (concrete)

How about other entities?30

30An example was shown aboveJ. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--92

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

Some Practice Questions. . .

What (if any) kind of polymorphism?

1 Operator “>=” in PASCAL?2 . . . and in C?3 . . . and in C++?4 Function succ in PASCAL?5 Function chr in PASCAL?6 The array type constructor in

PASCAL?

7 The for. . .to iterativecommand in PASCAL?

8 Procedure new in PASCAL?9 . . . and procedure dispose?

10 Operator “+” in PASCAL?11 and in C?12 . . . and in JAVA?

What are all the types of this value?

1 true in PASCAL?2 June in PASCAL?3 0 in PASCAL?

4 . . . and in C?5 . . . and in C++?6 “{}” in C++?

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--93

3.Advanced Typing 3.3. Polymorphism / 3.3.7. Case Studies / Exercises

More Questions. . .

1 Write a PASCAL program that while using ranges makes a type error?2 Is the type error flagged at compile time? At runtime? How?3 Write a C++ program in which an enum variable is overflowed.4 Is the type error flagged at compile time? At runtime? How?5 Repeat the above two questions for PASCAL.6 PASCAL has this problem of programs not being able to read files.

Explain this problem.7 With respect to this problem, why does it still make sense to allow

functions such as eof which can take many different types of files?8 Classify the polymorphism kind (if any) of all of PASCAL’s pre-defined

functions, constants, and procedures.

J. GIL (TECHNION–IIT) CS 234319: Programming Languages Nov.‘13 3.3--94