polymorphism (ad-hoc and universal)

20
Polymorphism (Ad-hoc and Universal Sérgio Souza Costa Universidade Federaldo Maranhão 3 de julho de 2016 Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 1 / 20

Upload: sergio-souza-costa

Post on 17-Feb-2017

158 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Polymorphism (Ad-hoc and Universal)

Polymorphism (Ad-hoc and Universal

Sérgio Souza Costa

Universidade Federaldo Maranhão

3 de julho de 2016

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 1 / 20

Page 2: Polymorphism (Ad-hoc and Universal)

Based in On understanding types, data abstraction, and polymorphism (Luca Cardelli and PeterWegner)

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 2 / 20

Page 3: Polymorphism (Ad-hoc and Universal)

Summary

Static and Strong TypingPolymorphismKinds of PolymorphismAd-hoc - OverloadingAd-hoc - CoercionParametric polymorphismInclusion polymorphism

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 3 / 20

Page 4: Polymorphism (Ad-hoc and Universal)

Static and Strong Typing

In mathematics as in programming, types impose constraints which help to enforcecorrectness.To prevent type violations, we generally impose a static type structure on programs. Typesare associated with constants, operators, variables, and function symbols.A type inference system can be used to infer the types of expressions when little or no typeinformation is given explicitly.In languages like Pascal and Ada, the type of variables and function symbols is defined byredundant declarations and the compiler can check the consistency of definition and use.In languages like ML, explicit declarations are avoided wherever possible and the systemmay infer the type of expressions from local context, while still establishing

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 4 / 20

Page 5: Polymorphism (Ad-hoc and Universal)

Static and Strong Typing

DefiniçãoProgramming languages in which the type of every expression can be determined by staticprogram analysis are said to be statically typed.

Static typing is a useful property, but the requirement that all variables and expressions arebound to a type at compile time is sometimes too restrictive.It may be replaced by the weaker requirement that all expressions are guaranteed to betype-consistent although the type itself may be statically unknown; this can be generallydone by introducing some run-time type checking.

DefiniçãoLanguages in which all expressions are type-consistent are called strongly typed languages.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 5 / 20

Page 6: Polymorphism (Ad-hoc and Universal)

Static and Strong Typing

Pros:In general, we should strive for strong typing, and adopt static typing whenever possible..Static typing allows type inconsistencies to be discovered at compile time and guaranteesthat executed programs are type-consistent.It facilitates early detection of type errors and allows greater execution-time efficiency. Itenforces a programming discipline on the programmer that makes programs morestructured and easier to read.

Cons:Static typing may also lead to a loss of flexibility and expressive power by prematurelyconstraining the behavior of objects to that associated with a particular type.Traditional statically typed systems exclude programming techniques which, althoughsound, are incompatible with early binding of program objects to a specific type. Forexample they exclude generic procedures, e.g. sorting, that capture the structure of analgorithm uniformly applicable to a range of types.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 6 / 20

Page 7: Polymorphism (Ad-hoc and Universal)

Polymorphism

Conventional typed languages, such as Pascal, are based on the idea that functions andprocedures, and hence their operands, have a unique type. Such languages are said to bemonomorphic, in the sense that every value and variable can be interpreted to be ofone and only one type.Polymorphic languages in which some values and variables may have more than onetype.Polymorphic functions are functions whose operands (actual parameters) can have morethan one type.Polymorphic types are types whose operations are applicable to values of more than onetype.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 7 / 20

Page 8: Polymorphism (Ad-hoc and Universal)

Kinds of Polymorphism

Cardelli classification

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 8 / 20

Page 9: Polymorphism (Ad-hoc and Universal)

Kinds of Polymorphism

Ad-hoc polymorphism is obtained when a function works, or appears to work, onseveral different types (which may not exhibit a common structure) and may behave inunrelated ways for each type.Universally polymorphic functions will normally work on an infinite number of types(all the types having a given common structure), while an ad-hoc polymorphic functionwill only work on a finite set of different and potentially unrelated types.In terms of implementation, a universally polymorphic function will execute the samecode for arguments of any admissible type, while an ad-hoc polymorphic function mayexecute different code for each type of argument.Universal polymorphism is considered true polymorphism, while ad-hoc polymorphism issome kind of apparent polymorphism

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 9 / 20

Page 10: Polymorphism (Ad-hoc and Universal)

Ad-hoc - Overloading

In overloading the same variable name is used to denote different functions, and thecontext is used to decide which function is denoted by a particular instance of the name.Example (c++):

1 main(){2 int a = 2, b = 3;3 float x = 1.5, y = 3.4;4 a = a + b; // a = somaint (a, b);5 x = x + y; // x = somafloat (x, y);6 }

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 10 / 20

Page 11: Polymorphism (Ad-hoc and Universal)

Ad-hoc - Coercion

A coercion is instead a semantic operation which is needed to convert an argument to thetype expected by a function, in a situation which would otherwise result in a type error.Coercions can be provided statically, by automatically inserting them between argumentsand functions at compile time, or may have to be determined dynamically by run-timetests on the arguments.Implicit conversion between types.Example (c++):

1 main() {2 int w = 3;3 float x;4 float y = 5.2;5 x = x + y; // x = somafloat (x, y)6 x = x + w; // x = somafloat (x, intToFloat (w) );7 }

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 11 / 20

Page 12: Polymorphism (Ad-hoc and Universal)

Universal - Parametric polymorphism

DefiniçãoIn parametric polymorphism, a polymorphic function has an implicit or explicit type parameter,which determines the type of the argument for each application of that function.

Example in Javaclass Comparators {

public static <T extends Comparable<T>> T max (T a, T b) {if (a.compareTo(b) > 0) return a;else return b;

}}

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 12 / 20

Page 13: Polymorphism (Ad-hoc and Universal)

Universal - Parametric polymorphism

C++

1 template <class T>2 T maior (T a, T b) {3 return ( (a>b)? a : b );4 }

Haskell

1 maior :: (Ord a) => a -> a -> a2 maior a b3 | a > b = a4 | otherwise = b

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 13 / 20

Page 14: Polymorphism (Ad-hoc and Universal)

Universal - Parametric polymorphism

The functions that exhibit parametric polymorphism are also called generic functions.For example, the length function from lists of arbitrary type to integers is called a genericlength function.

1 length :: [a] -> Int

A generic function is one which can work for arguments of many types, generally doing thesame kind of work independently of the argument type.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 14 / 20

Page 15: Polymorphism (Ad-hoc and Universal)

Universal - Parametric polymorphism

Parametric type and operator overloading1 template <class T>2 class Point {3 public:4 T x, y;5 Point (T x1, T y1):x(x1),y(y1) {}6 Point operator + (Point& other) {7 return Point (x+other.x,y+other.y);8 }9 friend ostream& operator << (ostream& out, Point p) {

10 out << p.x << "-" << p.y << endl;11 return out;12 }13 };

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 15 / 20

Page 16: Polymorphism (Ad-hoc and Universal)

Universal - Parametric polymorphism

1 int main() {2 Point<string> p1("ab","cd");3 Point<string> p2("fg","de");4 Point<string> p3 = p1 + p2;5

6 cout << p3 << endl;7

8 return 0;9 }

ObservaçãoParametric polymorphism is supported in Java through Generic Types.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 16 / 20

Page 17: Polymorphism (Ad-hoc and Universal)

Inclusion polymorphism

DefiniçãoInclusion polymorphism is a type system in which a type may have subtypes, which inheritoperations from that type. Where a type T is a set of values, equipped with some operations.A subtype of T is a subset of the values of T , equipped with the same operations as T . Everyvalue of the subtype is also a value of type T , and therefore may be used in a context where avalue of type T is expected (David Watt).

In inclusion polymorphism an object can be viewed as belonging to many different classeswhich need not be disjoint, i.e. there may be inclusion of classes.Inclusion polymorphism as a relation among types which allows operations to be applied toobject of different types related by inclusion.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 17 / 20

Page 18: Polymorphism (Ad-hoc and Universal)

Inclusion polymorphism - Example

class Point {protected double x, y;public void draw () {. . .} // Draw this point.. . . // other methods

class Circle extends Point {private double r;public void draw () {. . .} //Draw this circle.. . . // other methods

class Rectangle extends Point {private double w, h;public void draw () {. . .} // Draw this rectangle.. . . // other methods

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 18 / 20

Page 19: Polymorphism (Ad-hoc and Universal)

Inclusion polymorphism - Example

Java allows objects of any subclass to be treated like objects of the superclass. Considerthe following variable:Point p;...p = new Point(3.0, 4.0);...p = new Circle(3.0, 4.0, 5.0);

This variable may refer to an object of class Point or any subclass of Point. In otherwords, this variable may refer to any value of type Point.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 19 / 20

Page 20: Polymorphism (Ad-hoc and Universal)

Inclusion polymorphism - Example

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 20 / 20