Structuring the Data. Structuring the Data

Similar documents
Fundamentals of Programming Languages

Sub- PPL Unit-II Class-SE Comp

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Data types. Definitions Aggregate constructors User-defined type definitions Types and storage Types and subtypes Type systems and type checking

CPSC 3740 Programming Languages University of Lethbridge. Data Types

Lecture 12: Data Types (and Some Leftover ML)

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Organization of Programming Languages CS3200 / 5200N. Lecture 06

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

Programming Languages

Basic Types & User Defined Types

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Chapter 6. Data Types ISBN

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

TYPES, VALUES AND DECLARATIONS

Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2

Types and Classes. I II From predefined (simple) and user-defined (composite) types via Abstract data types

Francesco Nidito. Programmazione Avanzata AA 2007/08

Polymorphism. Chapter Eight Modern Programming Languages, 2nd ed. 1

Data Types In Text: Ch C apter 6 1

Data Types (cont.) Subset. subtype in Ada. Powerset. set of in Pascal. implementations. CSE 3302 Programming Languages 10/1/2007

Advanced oo concepts Specialization of behaviour? Multiple inheritance - alternatives to. Inner classes Classes

int f(char a, char b) {

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

G Programming Languages Spring 2010 Lecture 8. Robert Grimm, New York University

Chapter 6. Data Types ISBN

Fundamentals of Programming Languages. Data Types Lecture 07 sl. dr. ing. Ciprian-Bogdan Chirila

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

COSC252: Programming Languages: Basic Semantics: Data Types. Jeremy Bolton, PhD Asst Teaching Professor

Names, Scopes, and Bindings II. Hwansoo Han

Programming Languages

Data Types The ML Type System

CS321 Languages and Compiler Design I Winter 2012 Lecture 13

Chapter 6. Data Types

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi

SE352b: Roadmap. SE352b Software Engineering Design Tools. W3: Programming Paradigms

CSE 452: Programming Languages. Where are we? Types: Intuitive Perspective. Data Types. High-level Programming Languages.

G Programming Languages - Fall 2012

22c:111 Programming Language Concepts. Fall Types I

G Programming Languages - Fall 2012

Imperative Programming

Types. Chapter Six Modern Programming Languages, 2nd ed. 1

A data type defines a collection of data objects and a set of predefined operations on those objects

IA010: Principles of Programming Languages

CS321 Languages and Compiler Design I. Fall 2013 Week 8: Types Andrew Tolmach Portland State University

Organization of Programming Languages CS320/520N. Lecture 06. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Programming Languages Third Edition. Chapter 7 Basic Semantics

COS 140: Foundations of Computer Science

Data Types. Data Types. Introduction. Data Types. Data Types. Data Types. Introduction

Chapter 5 Names, Binding, Type Checking and Scopes

Software II: Principles of Programming Languages

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Chapter 6. Structured Data Types. Topics. Structured Data Types. Vectors and Arrays. Vectors. Vectors: subscripts

BLM2031 Structured Programming. Zeyneb KURT

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

Static Checking and Type Systems

Types. What is a type?

HANDLING NONLOCAL REFERENCES

Other Features of Procedures

Types and Type Inference

Chapter 6. Data Types ISBN

CSCI-GA Scripting Languages

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

CSC 533: Organization of Programming Languages. Spring 2005

CSCI312 Principles of Programming Languages!

Lecture Notes on Programming Languages

CSc 520 Principles of Programming Languages

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Binding and Variables

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

Imperative Programming Languages (IPL)

Data Types. CSE 307 Principles of Programming Languages Stony Brook University

Types and Type Inference

CS558 Programming Languages

Chapter 5. Names, Bindings, and Scopes

Semantic Analysis and Type Checking

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

12 CREATING NEW TYPES

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

CS558 Programming Languages

Industrial Programming

Types, Type Inference and Unification

Informatica 3 Syntax and Semantics

Questions? Static Semantics. Static Semantics. Static Semantics. Next week on Wednesday (5 th of October) no

Chapter 6. Data Types. *modified by Stephanie Schwartz ISBN

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

CS 230 Programming Languages

Lecture 11: Subprograms & their implementation. Subprograms. Parameters

Principles of Programming Languages

CS558 Programming Languages

CA341 - Comparative Programming Languages

COS 140: Foundations of Computer Science

The compilation process is driven by the syntactic structure of the program as discovered by the parser

Types II. Hwansoo Han

Lists. Michael P. Fourman. February 2, 2010

Transcription:

2017-05-12 Structuring the Data Structuring the Data

2017-05-12 Structuring the Data 1 Why Use (Static, Strong) Types? hide machine representation improves programming style and maintainability consistent use of variables checked by compiler improves readability and correctness space requirements of variables known at compilation time improves memory efficiency and run-time performance resolve overloading at compilation time improves readability and performance

2017-05-12 Structuring the Data 2 Elementary Types usually: elementary type (not decomposable) = predefined type String in Ada is predefined, but not elementary: type String is array (Positive range <>) of Character enumeration types are elementary, but not predefined: type color = (red, blue, green); type color is (red, blue, green); enum color { red, blue, green }; Pascal Ada C

2017-05-12 Structuring the Data 3 Aggregates and Type Constructors aggregates are composed of several (elementary) data objects, e.g., arrays and records old languages like Fortran, Cobol: aggregates directly created (without aggregate types) more recent languages: new types created from existing types by using type constructors; aggregates are instances of these types created by the use of programmer-defined constructors (or sometimes directly)

2017-05-12 Structuring the Data 4 Cartesian Product cartesian producta 1 A n ofnsetsa 1,...,A n is the set of all n-tuples (a 1,...,a n ) witha i A i in programming languages: field names instead of indexes (C): typedef struct { int no_of_edges; float edge_size; } reg_polygon; reg_polygon a_pol = { 3, 3.14 }; fields are selected using dot-notation: a_pol.no_of_edges = 4;

2017-05-12 Structuring the Data 5 Finite Mapping mathematical function maps domain into range example: f: integer real finite mapping = function with finite domain definition of mapping as routine is intensional where rules define the values in the range definition of finite mapping as array is extensional where the values in the range are enumerated

2017-05-12 Structuring the Data 6 Array Types (Examples) exampe in C: char digits[10]; for (i=0; i<10; i++) digits[i] = ; it s an error if an index is not in the domain; in general, such errors show up at run-time examples in Pascal: var x: array[2..5] of integer; type manufacturer = (ibm, dec, hp, sun); type m_data = array[manufacturer] of integer; var m_profits, m_empl: m_data;

2017-05-12 Structuring the Data 7 Arrays (Examples) initialization of arrays in C and Ada: char digits[5] = { a, b, c, d, e }; X: array(integer range 2..6) of INTEGER := (0,2,0,5,-33); multi-dimensional arrays in C and Ada: int y[10][20]; Y: array(1..27, M..N) of INTEGER; array slicing in Ada: X(2..5) := X(3..6);

2017-05-12 Structuring the Data 8 Associative Data Structures in dynamically typed languages, array entries can be of different types exampe of associative data structure in SNOBOL4: T = TABLE() T< RED > = WAR T<6> = 25 T<4.6> = PEACE T<6> gives 25 and T< RED > gives WAR

2017-05-12 Structuring the Data 9 Union definition of union in C: union address { short int offset; long unsigned int absolute; }; remember which field ist set: enum descriptor {abs, rel}; typedef struct { address location; descriptor kind; } safe_address;

2017-05-12 Structuring the Data 10 Discriminated Union variant record in Pascal: natural = 0..maxint; address_type = (absolute, offset); safe_address = record case kind: address_type of absolute: (abs_addr: natural); offset: (off_addr: integer) end

2017-05-12 Structuring the Data 11 Powerset powerset = set of all subsets of a set in programming languages: set is type example in Pascal: type option = (list, optimize, save, exec); option_set = set of option; var active_options: option_set;... active_options := [optimize, save]; if exec in active_options then...

2017-05-12 Structuring the Data 12 Recursive Data Types examples based on sets: bin tree ={nil} (integer bin tree bin tree) int list ={nil} (integer int list) example of the use of lists in ML: fun find(el, nil) = false find(el, x:xs) = if el = x then true else find(el, xs) ;

2017-05-12 Structuring the Data 13 Recursive Data Type Examples exampes ist C and Ada: typedef struct list { type INT_LIST int val; type INT_LIST_REF is access INT_LIST; list* next; type INT_LIST is } int_list; record int_list* head; VAL : INTEGER; NEXT: INT_LIST_REF; end; HEAD: INT_LIST_REF;

2017-05-12 Structuring the Data 14 Unsafety of Pointers untyped pointers as in PL/I shall be replaced by typed pointers arithmetic operations on pointers as in C can be forbidden at the cost of reduced efficiency dangling references because of scope violations no address operator and all objects on heap; run-time checks difficult dangling references because of explicit deallocation only garbage collection instead of explicit deallocation pointers in non-discriminated unions use only discriminated unions

2017-05-12 Structuring the Data 15 Abstract Data Types example in C++: class point { public: point(int a, int b) { x = a; y = b; } void x_move(int a) { x += a; } void y_move(int b) { y += b; } void reset() { x = 0; y = 0; } private: int x, y; };

2017-05-12 Structuring the Data 16 Generic Abstract Data Type (C++) template<class T> class Stack { public: Stack(int sz) { top = s = new T[size = sz]; } ~Stack() { delete[] s; } void push(t el) { *top++ = el; } T pop() { return *--top; } private: int size; T *top, *s; } void foo() { Stack<int> int_st(30); Stack<item> item_st(100);... }

2017-05-12 Structuring the Data 17 Strong and Static Type Systems type system = set of rules specifying type consistency strong type system ensures type consistency, i.e., static type checking ensures type consistency at run-time static type system associates each expression statically with a type each static type system is also strong, but not each strong type system is static

2017-05-12 Structuring the Data 18 Type Compatibility is type S compatible with type T? (conformance, equivalence) name compatibility = only one type definition, otherwise incompatible, structural compatibility = types have corresponding structures name compatibility stronger than structural compatibility because of abstraction through (informal) intentions expressed by names C uses structural equivalence except for structs, Ada uses (almost only) name compatibility: IA: array (1..100) of INTEGER; IB: arrau (1..100) of INTEGER; -- not compatible with IA

2017-05-12 Structuring the Data 19 Structural Type Compatibility many possible ways to define structural type compatibility: type s1 is struct { int y; int w; } type s2 is struct { int y; int w; } type s3 is struct { int y; }

2017-05-12 Structuring the Data 20 Type Coercion in some languages some types are implicitly changed when the compiler detects an incompatibility example in C: int x; float z;... x = x + z; // coercion of x to float, result to int x = x + (int)z; // explicit type cast, no coercion

2017-05-12 Structuring the Data 21 Names and Constraints in Ada type IntVector is array (Integer range <>) of Integer; type VarRec (IsChar: Boolean) is record X: Float; case IsChar of when False => Y: Integer; True => U: Char; end case; end record; subtype Vec100 is IntVector(0..99); -- compat. with IntVector subtype VarRecChar is VarRec(True); -- compat. with VarRec subtype MyInt is Integer range -9..9; -- compat. with Integer

2017-05-12 Structuring the Data 22 Polymorphic Types monomorphic: each variable and expression has exactly one type polymorphic: variables and expressions can have several types kinds of polymorphism: universal polymorphism: ad-hoc polymorphism: parametric polymorphism (= genericity) inclusion polymorphism (= subtyping) overloading coercion

2017-05-12 Structuring the Data 23 Scalar Types in Ada type Small_Int is range -10..10; -- user-defined integer type Two_Digit is mod 100; -- modulo numb. (0..99) subtype Natural is Integer range 0..INTEGER LAST; subtype Positive is Integer range 1..INTEGER LAST; type Celsius is new Integer; -- incompatible to Integer type Farenheit is new Integer; type MyFloat is digits 10; -- user-defined floating point type Fix_Pt is delta 0.01 range 0.0..100.0; -- fixed point type Dec_Pt is delta 0.01 digits 3; -- accurate fixed point type Week is (Sun, Mon, Tue, Wed, Thu, Fri, Sat); type Daily is array (Week) of Integer; type At_Work is array (Week range Mon..Fri) of Integer;

2017-05-12 Structuring the Data 24 Discriminated Union in Ada type Address_Type is (Absolute, Offset); type Safe_Address is record (Kind: Address_Type := Absolute) case Kind is when Absolute => Abs_Addr: Natural; when Offset => Off_Addr: Integer; end case; end record;

2017-05-12 Structuring the Data 25 Pointers in Ada T: Tree_Ref;... T := new Bin_Tree_Node; T.all := (Info => 0, Left => null, Right => null) type Message_Routine is access procedure(m: String); Give_Message: Message_Routine;... Give_Message := Print_This Access; Give_Message.all("This is not an error"); Structure: array (1..10) of aliased Component; type ComponentPtr is access all Component; Mine, Yours: ComponentPtr;... Mine := Structure(1) Access; Yours := Structure(2) Access;

2017-05-12 Modularity and Programming in the Large Modularity and Programming in the Large

2017-05-12 Modularity and Programming in the Large 1 Package Specification in Ada package Dictionary is procedure Insert(C:String; I:Integer); function Lookup(C:String) return Integer; end Dictionary;

2017-05-12 Modularity and Programming in the Large 2 Package Body in Ada package body Dictionary is type Node; type Node_Ptr is access Node; type Node is record Name: String; Id: Integer; Next: Node_Ptr; end record; Root: Node_Ptr; procedure Insert(C:String; I:Integer) is begin... end Insert; function Lookup(C:String) return Integer is begin... end Lookup; begin Root := null; end Dictionary;

2017-05-12 Modularity and Programming in the Large 3 Use of Package in Ada with Dictionary; use Dictionary; procedure Main is Code: Integer; begin Insert("volleyball", 1); Insert("football", 2);... Code := Lookup("football");... end Main;

2017-05-12 Modularity and Programming in the Large 4 Use of Package in Ada with X; with T; package T is procedure U(...) is C: Integer;... procedure D(...);... T.D(...)... end T;... T.C... end U; package body T is with T;... use T;... procedure U(...) is...... end T;... D(...)...... C... end U;

2017-05-12 Modularity and Programming in the Large 5 Package Specification with Private Part package Dictionary is type Dict is private; procedure Insert(D: in out Dict; C: String; I: Integer); function Lookup(D: Dict; C: String) return Integer; private type Node; type Node_Ptr is access Node; type Node is record Name: String; Id: Integer; Next: Node_Ptr; end record; type Dict is new Node_Ptr; end Dictionary;

2017-05-12 Modularity and Programming in the Large 6 Module in ML structure Dictionary = struct exception NotFound; val create: (string * int) list = nil; fun insert(c:string, i:int, nil:(string*int)list) = [(c,i)] insert(c, i, (cc,ii)::cs) = if c = cc then (c,i)::cs else (cc,ii)::insert(c,i,cs); fun lookup(c:string, nil:(string*int)list) = raise NotFound lookup(c, (cc,ii)::cs) = if c = cc then ii else lookup(c,cs); end;

2017-05-12 Modularity and Programming in the Large 7 Use of Module in ML val d = Dictionary.create val e = Dictionary.insert("X", 7, d);... Dictionary.lookup("X", e);

2017-05-12 Modularity and Programming in the Large 8 Signature in ML signature DictLookupSig = sig exception NotFound; val lookup: string * (string * int) list -> int end;

2017-05-12 Modularity and Programming in the Large 9 Module Constrainted by Signature in ML structure LookupDict: DictLookupSig = Dictionary; val l = LookupDict.create; (* not allowed *) val d = Dictionary.create; val e = Dictionary.insert("X", 7, d); val v = LookupDict.lookup("X", e); val k = LookupDict.insert("Y", 8, e); (* not allowed *)

2017-05-12 Modularity and Programming in the Large 10 Generic Module in ML structure Dictionary = struct exception NotFound; val create = nil; fun insert(c, i, nil) = [(c,i)] insert(c, i, (cc,ii)::cs) = if c = cc then (c,i)::cs else (cc,ii)::insert(c,i,cs); fun lookup(c, nil) = raise NotFound lookup(c, (cc,ii)::cs) = if c = cc then ii else lookup(c,cs); end;