Informatica 3 -...
Transcript of Informatica 3 -...
![Page 1: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/1.jpg)
9/15/0710/27/07
Marcello Restelli
Laurea in Ingegneria InformaticaPolitecnico di Milano
Informatica 3
![Page 2: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/2.jpg)
2
Structuring the Data
In a programming language are organized through the concept of typeType specifies a set of values and a set of operations for a variableProgram entities (or objects) are instances of typesType available in programming languages are
Built-in types and primitive typesData aggregates and constructorsUser defined types and abstract data typesType systems
Examples of declarationx, y, z: T;T x, y, z;
![Page 3: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/3.jpg)
3
Built-in Types
All the programming languages provide a set of built-in typesbooleancharactersintegersreals
Allow to classify the data used in a programProtect data from illegal operations
![Page 4: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/4.jpg)
4
Advantages of Built-in Types
Hiding of underlying representationname versus structurespecification versus implementationIndependence of client from serverWe can change implementation without changing interface and use
which implies modifiability and portability
Correct use of variables can be checked at compile time (if type is known)
improve code reliabilitynot any error can be identified at compile-time
Examplex := i/j can be checked for type correctness but the condition j!=0 cannot be checked
Resolution of overloaded operators at compile-time x := y * z;
![Page 5: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/5.jpg)
5
Primitive Types
Primitive types are atomic typesthey are usually defined by language/machine
Often they are the built-in types, but there are exceptions (e.g., char and strings in Ada)It is possible to define new types
define the values for the new typeoperations (depending on the programming language)Example
enumerative types
![Page 6: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/6.jpg)
6
Enumerative Types
Ordinal type whose values are defined by the userThe only admissible operations are
succ, pred, <
Exampleenum color {white, yellow, red, green};
The elements are sorted according to their declaration orderwhite < yellow < red < green
![Page 7: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/7.jpg)
7
Data aggregate
From primitive types we can derive aggregate typesEach aggregate has a nameIt is possible to aggregate homogeneous and heterogeneous typeConstructors for compound values and typesOperations on entire aggregateSelection of components possible
![Page 8: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/8.jpg)
8
Type Constructors (1)
Cartesian productA1 x A2 x ... x AnExamples
complex numbersCartesian point
Language constructors: record, struct, ...
Finite mapping maps a domain type into a range type: DT→RTDomain is finiteArrays of most languagesIs DT fixed at
Compile-time?
Object creation/ instantiation time?Or object manipulation time?
Is DT only subrange of integers?Is DT extensible at runtime?
![Page 9: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/9.jpg)
9
Type Constructors (2)
(Discriminated) unionA1 A2 A3∪ ∪Disjunction of valuesSimilar to Cartesian products but fields are mutually exclusiveWhat is the type of the object at runtime?Requires runtime type checking for correct operation
union u (int i, float f);
Recursionis a structuring mechanism for defining aggregates whose size can grow arbitrarilyit can be obtained by means of pointers
one of the components is a pointer to the object
Example: typedef struct { int val; int_list* next;} int_list;int_list* head;
![Page 10: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/10.jpg)
10
Problem with Pointers
Pointers are often used to implement recursive structuresPointers establish a dependency between two objects. It is important for the object to exist as long as the pointer points to itMemory leaks
(object exists, but can’t be reached)
Dangling pointers(pointer to deallocated area)
int* px;void trouble ();{ int x; ... px= &x; ... return;}
main( ){ trouble (); // x is deallocated // px is dangling}
![Page 11: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/11.jpg)
11
User-defined Types
Primitive or aggregated types that are associated to a nameExample
type declaration: enum bool {FALSE, TRUE};
variable declaration: bool b;
Advantagesreadabilitymodifiabilityfactorization(limited) specification of the semantics of a variable
Disadvantagesthe new type is not protected against illegal and undesired operationsinternal representation is visible
![Page 12: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/12.jpg)
12
Abstract Data Types
ADT is a data type that is accessible only through its interfaceDeveloping programs by means of high-level abstractions
a distinction is kept between conceptual transformations of data and their representation and their algorithmic implementationabstract mechanisms for specific applications useful to solve problems in many different applicative domains
![Page 13: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/13.jpg)
13
ADT in C++
Class constructextension of the struct construct in which fields can be both data and routinesonly some of the data/routines can be accessible by the extern
other fields are hidden
a class has both a public and a private partthe set of public functions is the interface of the classdefinition and implementation can be compiled separately
definition ≠ interface
class point {private: float x, y;
public: point (float a, float b) {x = a; y = b;}; void x_move (float a) {x += a;}; void y_move (float b) {y += b;}; void reset () { x = y = 0.0;};};
![Page 14: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/14.jpg)
14
ADT in C++: An Example
A stack is an ADT in which it is possible
to insert an element (push)increases the stack size of 1
to delete the last inserted element (pop)
decreases the stack size of 1
LIFO policy
class stack{ private: int* p; int* top; int size; public: stack (int n) {top = p = new int[size = n];} ~stack() {delete [ ] p;} void push(int i) {(*top++) = i;} int pop() {return *--top;} …}
![Page 15: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/15.jpg)
15
Object Lifetime
At constructionObject is allocated,Then, attributes are initialized as specified by constructorAllocation can be automatic or explicit (via new)
At destructionObject attributes are cleanedThen, the object is deallocatedDeallocation can be automatic or explicit (via delete)
![Page 16: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/16.jpg)
16
Object Constructor
Constructors have the same name as type being definedThere can be many, with different signaturesDefault constructors are provided if none explicitly definedExample:
stack (int n){ top = p = new int[size = n];}
![Page 17: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/17.jpg)
17
Copy Constructor
It is a special kind of constructorIt differs from assignment since object does not exist yetBuilds an object from an existing one, whose copy is constructedIt is also used for parameter passing
Two notationspoint p1 = p2;point p1(p2);
point(const point& p) { // x and y private parts // of the object itself x = p.x; y = p.y;}
![Page 18: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/18.jpg)
18
Object Destructor
Destructors have the same name as the class being defined, prefixed by ~Performs cleanup actions after last use of an objectThere can be only one destructor for a classDefault destructor exists if not providedExample:
~stack() {delete [] p;}
![Page 19: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/19.jpg)
19
Assignment
C++ uses memberwise copy of attributes by default;We say that copy is shallowThis works well for classes like point, but if the class contains pointers...
We need a customized assignment operator
void f(){ stack s1(20), s2(30); s1 = s2; //array referred to by //s1 is lost it is not // deleted upon exit //from block};
![Page 20: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/20.jpg)
20
Assignment Operations for Objects
class stack{ ... public: stack (int n) {top = p = new int[size = n];} ~stack() {delete [ ] p;} stack& operator=(const stack&); ...}
stack& stack::operator=(const stack& s){ //to cover s = s; if (this != &s) { delete [ ] p; p = s.p; top = s.top; size = s.size; return *this; }}
![Page 21: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/21.jpg)
21
Assignment Operations for Objects by Cloning
class stack{ ... public: stack (int n) {top = p = new int[size = n];} ~stack() {delete [ ] p;} stack& operator=(const stack&); ...}
stack& stack::operator=(const stack& s){ //to cover s = s; if (this != &s) { delete [ ] p; p = new int[size = s.size]; top = p + s.top - s.p; for (int i = 0; i<(top-p); ++i) {p[i] = s.p[i];} return *this; }}
![Page 22: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/22.jpg)
22
Friend Functions in C++
Suppose we have two classes for vector and matrixWe need to define multiplication between a vector with a matrixWhere should it be placed?
Does it belong to matrix?Does it belong to vector?
Global? No, it would have no access to private attributesMultiplication is declared friend of bothclass matrix { ... friend vector multiplication(const matrix&, const vector&); //can be placed in either private or public part}class vector { ... friend vector multiplication(const matrix&, const vector&); //can be placed in either private or public part}
![Page 23: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/23.jpg)
23
Friend Functions in C++
Suppose we have two classes for vector and matrixWe need to define multiplication between a vector with a matrixWhere should it be placed?
Does it belong to matrix?Does it belong to vector?
Global? No, it would have no access to private attributesMultiplication is declared friend of bothvector multiplication(const matrix& m, const vector& v);{ // assume 0..3 matrix and vector vector r; for (int i = 0; i<3, i++) { //r[i] = m[i] * v r.elem(i) = 0 for (int j = 0, j<3; j++) r.elem(i) += m.elem(i, j) * v.elem(j); } return r;}
![Page 24: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/24.jpg)
24
Generic ADT
template<class T>class Stack{public: // constructor Stack(int sz) {top = s = new T[size = sz];} // destructor ~Stack() {delete[ ] s;} void push(T el) {*top++ = el;} T pop() {return *--top;} int length() {return top - s;}private: int size; T* top; T* s;};
void foo(){ Stack<int> int_st(30); Stack<item> item_st(100); ... int_st.push(9); ...}
ADT that are parametric w.r.t. the type of their behaviorC++: templates
![Page 25: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/25.jpg)
25
Generic Functions and Algorithms
C++ allows modularization based on functions, not only classesFunctions may be generic, i.e., generic functions, generic algorithmsStandard Template Library
Generic containersGeneric algorithms
![Page 26: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/26.jpg)
26
Generic Functions
template <class T>void swap(T& a, T& b){ T temp = a; a = b; b = temp;}
int i, j;char x, y;pair<int,string> p1, p2;...//swap integersswap(i, j);//swap charactersswap(x, y);// swap pairsswap(p1, p2);
![Page 27: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/27.jpg)
27
Java without Generics
public class oStack { private List stack = new ArrayList(); public void push(Object a) {stack.add(a);}; public Object top(){return stack.get(stack.size()-1);}; public void pop() {stack.remove(stack.size()-1);}; public String toString() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append('['); Iterator iterator = stack.iterator(); while (iterator.hasNext()) stringBuffer.append(iterator.next() + " "); stringBuffer.append(']'); return stringBuffer.toString(); }}
![Page 28: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/28.jpg)
28
Java without Generics
public class Example { public static void main(String[] args) { oStack IntegerStack = new oStack(); Integer top; IntegerStack.push(new Integer(3)); IntegerStack.push(new Integer(4)); IntegerStack.push(new Integer(5)); System.out.println(IntegerStack); top = (Integer) IntegerStack.top(); //** IntegerStack.pop(); System.out.println(IntegerStack); }}
![Page 29: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/29.jpg)
29
Java Generic ADT
class gStack<T>{ private List<T> stack = new ArrayList<T>(); public void push(T a) { stack.add(a); }; public T top() { return stack.get(stack.size()-1);}; public void pop() { stack.remove(stack.size()-1); }; public String toString() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append('['); for (T el : stack) stringBuffer.append(iterator.next() + ""); stringBuffer.append(']'); return stringBuffer.toString(); }}
![Page 30: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/30.jpg)
30
Java Generic ADT
class Example{ public static void main(String [] args) { gStack<Integer> IntegerStack = new gStack<Integer>(); Integer top; IntegerStack.push(new Integer(3)); IntegerStack.push(new Integer(4)); IntegerStack.push(new Integer(5)); System.out.println(IntegerStack); top = IntegerStack.top(); IntegerStack.pop(); System.out.println(IntegerStack); }}
![Page 31: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/31.jpg)
31
Java Generics: Implementation
Generics are implemented by the Java compiler as a front-end conversion called erasureErasure is the process of translating or rewriting code that uses generics into non-generic codeThus erasure maps the new syntax to the current JVM specificationThis conversion erases all generic type information all information between angle brackets is erased. For example, LinkedList<Integer> will become LinkedList. Uses of other type variables are replaced by the upper bound of the type variable (for example, Object), and when the resulting code is not type correct, a cast to the appropriate type is inserted.
![Page 32: Informatica 3 - home.deib.polimi.ithome.deib.polimi.it/restelli/MyWebSite/pdf/DataTypes.pdfInformatica 3. 2 Structuring the Data In a programming language are organized through the](https://reader034.fdocuments.us/reader034/viewer/2022050717/5e15ba71a72d7a68237e9d19/html5/thumbnails/32.jpg)
32
Java Generics vs C++ Template
Java generics look like the C++ templates, but they are not the same.Java Generics
They provide compile-time type safety and eliminate the need for casts.The main difference is encapsulation: errors are flagged where they occur and not later at some use site, and source code is not exposed to clients.Use type erasure: the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time.
C++ templateThey are macrosWhenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class.