Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 of Programming Languages by Ravi Sethi.

Similar presentations


Presentation on theme: "Chapter 4 of Programming Languages by Ravi Sethi."— Presentation transcript:

1 Chapter 4 of Programming Languages by Ravi Sethi

2 TYPES:DATA REPRESENTATION The Role of TypesThe Role of Types Basic TypesBasic Types Arrays: Sequences of ElementsArrays: Sequences of Elements Records: Named FieldsRecords: Named Fields Unions and Variant RecordsUnions and Variant Records SetsSets Pointers: Efficiency and Dynamic AllocationPointers: Efficiency and Dynamic Allocation Two String TablesTwo String Tables Types and Error CheckingTypes and Error Checking

3 THE ROLE OF TYPES Data objects and Data representationData objects and Data representation Objects in an application have corresponding representations in a program. Objects in an application have corresponding representations in a program. Example: correspondence between application and program Example: correspondence between application and program application program application program data January 31 31 data January 31 31 data May 6 126 data May 6 126 variable d n(integer #) variable d n(integer #) operation tomorrow (d) n+1 operation tomorrow (d) n+1 Values and Their TypesValues and Their Types 1. Basic type 1. Basic type 2. Constructed type 2. Constructed type

4 THE ROLE OF TYPES(cont’d) Type ExpressionType Expression a) Describes how a data representation is built up a) Describes how a data representation is built up B) Can be used to B) Can be used to 1. Represent data objects 1. Represent data objects 2. Lay out values in the underlying machine 2. Lay out values in the underlying machine 3. Check that operators are applied properly within expression 3. Check that operators are applied properly within expression Static Layout DecisionStatic Layout Decision (next slide) (next slide) A Preview of Type Names, Arrays, and RecordsA Preview of Type Names, Arrays, and Records 1. Type names: boolean, char, integer, real 1. Type names: boolean, char, integer, real 2. Arrays: a sequence of elements 2. Arrays: a sequence of elements 3. Records: a set of components, each with its own type 3. Records: a set of components, each with its own type

5 THE ROLE OF TYPES(cont’d)

6 BASIC TYPES Enumeration : a finite sequence of names written between parenthesesEnumeration : a finite sequence of names written between parentheses type day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun); type day = (Mon, Tue, Wed, Thu, Fir, Sat, Sun); Integers and RealsIntegers and Reals Short-Circuit Evaluation of Boolean ExpressionsShort-Circuit Evaluation of Boolean Expressions Example : While (i >= 0 && x != A[ i ]) i = i-1 ; Example : While (i >= 0 && x != A[ i ]) i = i-1 ; Subranges : a special case of basic types that restrict the range of values of an existing type - weekends, weekdaysSubranges : a special case of basic types that restrict the range of values of an existing type - weekends, weekdays

7 BASIC TYPES (cont’d) Programming Style: Characters and Type ConversionProgramming Style: Characters and Type Conversion Example : Example : C : characters are implicitly coerced to integers C : characters are implicitly coerced to integers int c; int c; c = getchar(); -> coerced to an int c = getchar(); -> coerced to an int Pascal : Conversion will be done explicitly Pascal : Conversion will be done explicitly c = chr(ord(c)) c = chr(ord(c)) i = ord(chr(i)) i = ord(chr(i))

8 ARRAYS: SEQUENCES OF ELEMENTS Efficient access and storage allocationEfficient access and storage allocation Indexed by integers or enumerationsIndexed by integers or enumerations Array layoutArray layout 1. Elements appear in consecutive location in the underlying machine 1. Elements appear in consecutive location in the underlying machine 2. Elements can be computed in two parts 2. Elements can be computed in two parts a) Pre-computation a) Pre-computation b) Run time b) Run time 3. Arrays of Arrays : row-major layout, column-major layout 3. Arrays of Arrays : row-major layout, column-major layout

9 ARRAYS: SEQUENCES OF ELEMENTS (cont’d) Array BoundsArray Bounds a) Computed at compile time (Static evaluation) a) Computed at compile time (Static evaluation) b) Computed at run time (Dynamic evaluation) b) Computed at run time (Dynamic evaluation) Array Values and Initialization : a sequence of values for array elementsArray Values and Initialization : a sequence of values for array elements Example: int coin[] = { 1, 5, 10, 25, 50, 100 }; Example: int coin[] = { 1, 5, 10, 25, 50, 100 };

10 RECORDS: NAMED FIELDS A record type is a templateA record type is a template A Variable declaration allocates storageA Variable declaration allocates storage Operations on RecordsOperations on Records Example : z. re := x. re + y. re Example : z. re := x. re + y. re A comparison of Arrays and RecordsA comparison of Arrays and Records arraysrecords arraysrecords--------------------------------------------------------------------------------------------- component types homogeneousheterogeneous component selectors expressions evaluated names known at at run time compile time at run time compile time

11 UNIONS AND VARIANT RECORDS Union : a special case of a variant record with an empty common partUnion : a special case of a variant record with an empty common part Variant record : a part common to all records of that type and a variant partVariant record : a part common to all records of that type and a variant part figure 4.7 (next slide)figure 4.7 (next slide)

12 UNIONS AND VARIANT RECORDS(cont’d)

13 Layout of Variant RecordsLayout of Variant Records 1. Fixed Part 1. Fixed Part 2. Tag Field 2. Tag Field 3. Variant Part 3. Variant Part Variant Records compromise type safetyVariant Records compromise type safety

14 SETS Set Values:in Pascal, All elements must be of the same simple typeSet Values:in Pascal, All elements must be of the same simple type Set Types: Type set of S represents subsets of SSet Types: Type set of S represents subsets of S Example: var A : set of [1..3] Example: var A : set of [1..3] A can denote one of the following sets: A can denote one of the following sets: [ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3] [ ],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3] A set of n elements: implemented as a bit vector of length nA set of n elements: implemented as a bit vector of length n The basic operation on set is a membership testThe basic operation on set is a membership test

15 POINTERS: EFFICIENCY AND DYNAMIC ALLOCATION More efficient to move or copy a pointer to the data structureMore efficient to move or copy a pointer to the data structure Dynamically Implemented to use in data structureDynamically Implemented to use in data structure First-class citizensFirst-class citizens Pointer type must be declared before usedPointer type must be declared before used Dereferencing operation : indirect accessDereferencing operation : indirect access Example Pascal: dynamic allocation on the heap, dereferencing, assignment, equality testing, deallocation Example Pascal: dynamic allocation on the heap, dereferencing, assignment, equality testing, deallocation Serve as links between cells (linked lists)Serve as links between cells (linked lists) Type and layout of storage are known statically before a program runsType and layout of storage are known statically before a program runs

16 POINTERS: EFFICIENCY AND DYNAMIC ALLOCATION(cont’d) The pointer operations affect access to storageThe pointer operations affect access to storage Dangling pointer is a pointer to storage that is being used for another purpose (deallocate the storage, but the reference to the pointer is still there)Dangling pointer is a pointer to storage that is being used for another purpose (deallocate the storage, but the reference to the pointer is still there) Pascal restricts pointer operations (only new and dispose); C stresses flexibilityPascal restricts pointer operations (only new and dispose); C stresses flexibility Rearranged inexpensivelyRearranged inexpensively

17 TWO STRING TABLES From a distance, types in Pascal and C are very similar, both have arrays, records and pointers. Differences in the treatment of pointers, lead to differences in style. The variable-length string application is famous and is used to show the differences (section 4.8)From a distance, types in Pascal and C are very similar, both have arrays, records and pointers. Differences in the treatment of pointers, lead to differences in style. The variable-length string application is famous and is used to show the differences (section 4.8) PascalPascal TeXTeX trofftroff WordWord all the words are in a pool (buffer), the words are index through an array called start which contains the beginning position of the word in the pool starting at 0 so start[0] = 0 and pool[start[0]] is the ’T’all the words are in a pool (buffer), the words are index through an array called start which contains the beginning position of the word in the pool starting at 0 so start[0] = 0 and pool[start[0]] is the ’T’ Indirect access through an array Indirect access through an array Integers as pointers - disadvantage compiler cannot check that it is a character Integers as pointers - disadvantage compiler cannot check that it is a character

18 TWO STRING TABLES From Yacc - Yet another Compiler CompilerFrom Yacc - Yet another Compiler Compiler start is the actual pointer address in pool not just an indexstart is the actual pointer address in pool not just an index C 1. Indirect access through pointers 1. Indirect access through pointers 2. Array name : pointer to a zeroth element - operations on pointers in C allow successive characters in a string to be accessed 2. Array name : pointer to a zeroth element - operations on pointers in C allow successive characters in a string to be accessed 3. Dereferencing and yielding operators 3. Dereferencing and yielding operators Example: p = &x; Example: p = &x; *p = *p + 1; is same as x = x + 1; *p = *p + 1; is same as x = x + 1;

19 TYPES AND ERROR CHECKING Types extend from values to expressions, the type of an expression x + y can be inferred from the types x and yTypes extend from values to expressions, the type of an expression x + y can be inferred from the types x and y Types of variable bindingsTypes of variable bindings 1. Static or early bindings 1. Static or early bindings 2. Dynamic or late bindings 2. Dynamic or late bindings Pascal has static bindings of types and dynamic bindings of values to variables. Lisp has dynamic binding of both values and types Pascal has static bindings of types and dynamic bindings of values to variables. Lisp has dynamic binding of both values and types Type systems : a set of rulesType systems : a set of rules Basic rule of type checkingBasic rule of type checking 1. Overloading : Multiple Meanings 1. Overloading : Multiple Meanings 2. Coercion : conversion from one type to another 2. Coercion : conversion from one type to another 3. Polymorphism : parameterized type 3. Polymorphism : parameterized type

20 TYPES AND ERROR CHECKING(cont’d) Type names and type equivalenceType names and type equivalence Example : Example : x, y : array [0..9] of integer x, y : array [0..9] of integer z : array [0..9] of integer z : array [0..9] of integer In Pascal, x and y have the same type, but z does not In Pascal, x and y have the same type, but z does not * Structural Equivalence * Structural Equivalence 1. A type name is structurally equivalent to itself 1. A type name is structurally equivalent to itself 2. Two types are formed by applying the same type constructor 2. Two types are formed by applying the same type constructor 3. After a type declaration, type n = T 3. After a type declaration, type n = T

21 TYPES AND ERROR CHECKING(cont’d) * Forms of Name Equivalence * Forms of Name Equivalence 1. Pure name equivalence 1. Pure name equivalence 2. Transitive name equivalence, type S = integer; T = S; U = integer; 2. Transitive name equivalence, type S = integer; T = S; U = integer; 3. Type expression equivalence 3. Type expression equivalence * Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like Modula-2 * Type Equivalence - sometimes left ambiguous in Pascal, sometimes given rules like Modula-2 * Circular Types : linked data structures give rise to recursive or circular * Circular Types : linked data structures give rise to recursive or circular types struct x { types struct x { int p; int p; struct x *next; struct x *next; }; };

22 TYPES AND ERROR CHECKING(cont’d) Static and Dynamic CheckingStatic and Dynamic Checking 1. Type error occurs if an operation is improperly applied 1. Type error occurs if an operation is improperly applied 2. Programs are checked statically 2. Programs are checked statically 3. Dynamic checking is done during program execution 3. Dynamic checking is done during program execution 4. Strong type ensures freedom from type errors 4. Strong type ensures freedom from type errors


Download ppt "Chapter 4 of Programming Languages by Ravi Sethi."

Similar presentations


Ads by Google