Programming Language Design Concepts Week VI Assist Prof



























![Example: Python object constructions § Assume: days_in_month = [0, 31, 28, 31, 30, 31] Example: Python object constructions § Assume: days_in_month = [0, 31, 28, 31, 30, 31]](https://slidetodoc.com/presentation_image_h2/b550359800214a92dc896bd9a99f5962/image-28.jpg)




- Slides: 32

Programming Language Design Concepts Week VI Assist. Prof. Tugba Onal-Suzek Adapted from David A. Watt’s slides http: //www. dcs. gla. ac. uk/~daw/books/PLDC/

Values and Types § Types of values. § Primitive, composite, recursive types. § Type systems: static vs dynamic typing, type equality, type completeness. § Expressions. § Implementation notes. 2 -2

Equivalence: two approaches § Two types: name and structural equivalence § Name Equivalence: based on declarations • More commonly used in current practice § Structural Equivalence: based on meaning/semantics behind the declarations. struct Position { int x, y; }; struct Position pos; struct Date { int m, d; }; struct Date today; void show (struct Date d); Here the call ‘‘show(today); ’’ would pass its type check, whether the language adopts structural or name equivalence. On the other hand, the call ‘‘show(pos); ’’ would pass its type check only if the language adopts structural equivalence.

typedef struct Comp { double x , y ; } Complex ; struct COMP { double x , y; }; struct Comp a; Complex b; struct COMP c ; /*. . . */ a=b; /* Valid , equal types */ a= c ; /* Compile error , incompatible types */ Confusingly, name and structural equivalence are used for different types in C: a type definition introduced by enum, struct, or union defines a new type, while a type definition introduced by typedef 2 -4 simply introduces a synonym for an existing type.

Data Types § A data type defines • a collection of data objects, and • a set of predefined operations on the objects type: integer operations: +, -, *, /, %, ^ § Evolution of Data Types • Early days: – all programming problems had to be modeled using only a few data types – FORTRAN I (1957) provides INTEGER, REAL, arrays • Current practice: – Users can define abstract data types (representation + operations)

Numeric Types § Integer • There may be as many as eight different integer types in a language (can you name them? ) • Negative numbers – How to implement them in hardware?

Representing Negative Integers 1 + (-1) = ? Ones complement, 8 bits § +1 is 0000 0001 § -1 is 1111 1110 Twos complement, 8 bits § If we use natural method of summation we get sum 1111 § +1 is 0000 0001 + § -1 is 1111 § If we use the natural method we get sum 0000 (and carry 1 which we disregard)

Floating Point § Floating Point • Approximate real numbers – Note: even 0. 1 cannot be represented exactly by a finite number of of binary digits! – Loss of accuracy when performing arithmetic operation • Languages for scientific use support at least two floating-point types; sometimes more 1. 63245 x 105 • Precision: accuracy of the fractional part • Range: combination of range of fraction & exponent • Most machines use IEEE Floating Point Standard 754 format

Floating Point Puzzle #include <stdio. h> #include <stdlib. h> #include <float. h> int main ( void ){ int x = 1; float f = 0. 1; double d = 0. 1; if (-d > -f) printf("Truen"); else printf("Falsen"); return 0; } True or False? • x == (int)(float) x True • x == (int)(double) x True • f == (float)(double) f True • d == (float) d False • f == -(-f); True • d > f False • -f > -d False • f > d True • -d > -f True • d == f False • (d+f)-d == f True

Floating Point Representation § Numerical Form • – 1 s M 2 E – Sign bit s determines whether number is negative or positive – Significand M normally a fractional value in range [1. 0, 2. 0). – Exponent E weights value by power of two s exp § Encoding • MSB is sign bit • exp field encodes E • frac field encodes M frac

Boolean Types § Could be implemented as bits, but often as bytes § Introduced in ALGOL 60 § Included in most general-purpose languages designed since 1960 § Ansi C (1989) • all operands with nonzero values are considered true, and zero is considered false § Advantage: readability

Character Strings § String Length • Static – FORTRAN 77, Ada, COBOL – e. g. (FORTRAN 90) CHARACTER (LEN = 15) NAME; • Limited Dynamic Length – C and C++ – actual length is indicated by a null character • Dynamic – SNOBOL 4, Perl, Java. Script § Evaluation (of character string types) • Aid to writability • As a primitive type with static length, they are inexpensive to provide • Dynamic length is nice, but is it worth the expense? § Implementation

Enumeration Data Types § Examples • Pascal – cannot reuse constants; can be used for array subscripts, for variables, case selectors; can be compared • Ada – constants can be reused (overloaded literals); disambiguate with context or type_name’(one of them) (e. g, Integer’Last) • C and C++ – enumeration values are coerced into integers when put in integer context • Java – does not include an enumeration type, but provides the Enumeration interface – can implement them as classes class colors { public final int red = 0; public final int blue = 1; }

Arrays § Indexing is a mapping from indices to elements • map(array_name, index_value_list) an element § Index Syntax • FORTRAN, PL/I, Ada use parentheses: A(3) • most other languages use brackets: A[3] § Subscript Types: • FORTRAN, C - integer only • Pascal - any ordinal type (integer, boolean, char, enum) • Ada - integer or enum (includes boolean and char) • Java - integer types only • Perl – any primitive type (associative array/hash)

Associative Arrays in Perl § Structure and Operations in Perl • Names begin with % • Literals are delimited by parentheses • %hi_temps = ("Monday" => 77, "Tuesday" => 79, …); • Subscripting is done using braces and keys • e. g. , $hi_temps{"Wednesday"} = 83; § Elements can be removed with delete • e. g. , delete $hi_temps{"Tuesday"};

Type completeness (1) § In principle, a value of any type can be: • assigned • composed with other values (as components of composite values) • passed as an argument (to a procedure or function) • returned as a function result. § But some (mainly older) PLs restrict which of these operations are applicable to certain types of values. § First-class values are values that are not restricted in which operations can be applied to them. 2 -16

Type completeness (2) § C: primitive structure array function can be assigned? √ √ ? ? can be composed? √ √ √ ? can be argument? √ √ ? ? can be function result? √ √ ? ? primitive record array function can be assigned? √ √ √ can be composed? √ √ √ can be argument? √ √ can be function result? √ ? ? § Pascal: 2 -17

Type completeness (3) § Ada: primitive record array function can be assigned? √ √ √ ? can be composed? √ √ √ ? can be argument? √ √ √ ? can be function result? √ √ √ ? primitive tuple list function can be composed? √ √ can be argument? √ √ can be function result? √ √ § Haskell: 2 -18

Example: type completeness (1) § Ada function and application code: type Complex is record x, y: Float; end record; function sum (c 1, c 2: Complex) return Complex is begin return (c 1. x+c 2. x, c 1. y+c 2. y); end; -- Print the complex sum of p, q, and r: put(sum(p, q), r)); 2 -19

Example: type completeness (2) § What if Ada function results were restricted to primitive values? procedure add (c 1, c 2: in Complex; c 3: out Complex) is begin c 3 : = (c 1. x+c 2. x, c 1. y+c 2. y); end; -- Print the complex sum of p, q, and r: declare t 1, t 2: Complex; begin add(p, q, t 1); add(t 1, r, t 2); put(t 2); end; 2 -20

Type Completeness Principle § Some PLs are more class-conscious than others: • C and Pascal are very class-conscious. • Ada is moderately class-conscious. • Haskell is not class-conscious at all (all values are first-class). § PL designers should bear in mind the Type Completeness Principle: No operation should be arbitrarily restricted in the types of its operands. § Arbitrarily is the key word here! • Restricting function results to be primitive is arbitrary. • Restricting the operands of and to be booleans is reasonable. 2 -21

Values and Types § Types of values. § Primitive, composite, recursive types. § Type systems: static vs dynamic typing, type completeness. § Expressions. § Implementation notes. 2 -22

Expressions § An expression is a PL construct that may be evaluated to yield a value. § Some fundamental expressions: • Literals: a fixed value of some type (i. e. 3, 14 , “What? ”) • A Constant access: a reference to a named constant, and yields the value of that constant. • A Variable access: a reference to a named variable, and yields the current value of that variable • Constructions: an expression that constructs a composite value from its component values. • Function calls: for F(E), F determines the function procedure to be applied, and the Expression E is evaluated to determine the argument. • Conditional expressions: From two or more subexpressions, one gets picked § Iterative expressions: performs a computation over a series of values 2 -23 (typically the components of an array or list), yielding some result.

Constructions § A construction is an expression that constructs a composite value from its component values. § In C, the component values are restricted to be literals Prior to C 99 there was no syntax in the language to write a struct literal so code below was not allowed Date someday ={jan, 1}; //was NOT allowed before C 99 § In Ada, Java, and Haskell, the component values are computed by evaluating subexpressions. 2 -24

Example: Remember C++ record and array constructions? § Record constructions: typedef enum Month {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec}; typedef enum Day_Number {1. . 31}; struct Date{ Month m; Day_Number d; }; Date someday ={jan, 1}; § Array construction: int size[] ={31, 28, 31, 30, 31}; if (is_leap(this_year)) size[feb] = 29; an array construction is used to initialize the variable size. 2 -25

Example: Haskell tuple and list constructions § Tuple constructions: today = (Dec, 25) m, d = today tomorrow = (m, d+1) § List construction: month. Lengths = [31, if is. Leap y then 29 else 28, 31, 30, 31] 2 -26

Example: Java object constructions § Assume: class Date { public int m, d; public Date (int m, int d) { this. m = m; } this. d = d; … } § Object constructions: Date today = new Date(12, 25); Date tomorrow = new Date(today. m, today. d+1); 2 -27
![Example Python object constructions Assume daysinmonth 0 31 28 31 30 31 Example: Python object constructions § Assume: days_in_month = [0, 31, 28, 31, 30, 31]](https://slidetodoc.com/presentation_image_h2/b550359800214a92dc896bd9a99f5962/image-28.jpg)
Example: Python object constructions § Assume: days_in_month = [0, 31, 28, 31, 30, 31] month_names = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] class Date(object): year = 1900 month = 1 day = 1 def __init__(self, year=1900, month=1, day=1): self. year, self. month, self. day = year, month, day def __str__(self, year=1900, month=1, day=1): self. year, self. month, self. day = year, month, day return str(year)+'-'+str(month). rjust(2, '0')+'-'+str(day). rjust(2, '0') def same_date_in_year(year, month, day): pass Object construction if __name__ == "__main__": date_one = Date( 1972, 3, 27 ) date_two = Date( 1998, 4, 13 ) date_three = Date( 1996, 4, 13 ) print "date_one is " + str(date_one) print "date_two is " + str(date_two) print "date_three is " + str(date_three) 2 -28

Function calls (1) § A function call computes a result by applying a function to some arguments. § If the function has a single argument, a function call typically has the form “F(E)”, or just “F E”, where F determines the function to be applied, and the expression E is evaluated to determine the argument. § In most PLs, F is just the identifier of a specific function. § In other PLs where functions are first-class values, F may be any expression yielding a function. E. g. , this Haskell function call: (if … then sin else cos)(x) 2 -29

Function calls (2) § If a function has n parameters, the function call typically has the form “F(E 1, …, En )”. We can view this function call as passing a single argument that is an n-tuple. 2 -30

In C++, infinite arguments are possible! 2 -31

In Java, infinite arguments are possible! However you can not have arguments of a different type after. For example, these below do not work: 2 -32