• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Lecture 4: Data Types
 

Lecture 4: Data Types

on

  • 1,755 views

Lecture 4 of course on concepts of programming languages

Lecture 4 of course on concepts of programming languages

Statistics

Views

Total Views
1,755
Views on SlideShare
512
Embed Views
1,243

Actions

Likes
0
Downloads
20
Comments
0

2 Embeds 1,243

http://department.st.ewi.tudelft.nl 1242
http://localhost 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Lecture 4: Data Types Lecture 4: Data Types Presentation Transcript

    • Lecture 4: Data Types TI1220 2012-2013 Concepts of Programming Languages Eelco Visser / TU Delft
    • Outline Type systems Structures in C Dynamic dispatch in Java Prototype inheritance in JavaScript Functional objects in Scala
    • Type Systems
    • type Bool x, y; x && y x || y !x operationsdata type: a collection of data values and a set of predefined operations on those values
    • type checking: the activity of ensuring thatthe operands of an operation are of compatibletypes. A compatible type is one that either is legal for the operator or is allowed under language rules to be implicitly converted (coerced) to a legal type type error: the application of an operator to an operand of an inappropriate type.
    • static type checking: all type bindings are defined statically, allowing type checking to be done at statically dynamic type checking: dynamic binding of types to variables requires checking types at run-time
    • a programming language is stronglytyped if type errors are always detected (statically or dynamically)
    • BooleanNumberIntegerFloat Primitive DatatypesCharacterString... Read Sebasta Chapter 6
    • record: an aggregate of elements in which the individual elements are identified by names and accessed through offsets from the beginning of the structure The fundamental difference between a record and an array is that record elements, or fields, are not referenced by indices, but by identifiers.
    • Structures in C
    • Structures in C structure tag struct point { int x; int y; member };A structure is a collection of one or more variables, possibly of different types,grouped together under a single name for convenient handling. (Structures arecalled ``records in some languages, notably Pascal.)
    • struct point { int x; int y;};struct rect { struct point pt1; struct point pt2;};struct point makepoint(int x, int y) { struct point temp; temp.x = x; temp.y = y; return temp;}struct point addpoint(struct point p1, struct point p2) { p1.x += p2.x; p1.y += p2.y; return p1;}
    • struct point origin, *pp;pp = &origin;printf("origin is (%d,%d)n", (*pp).x, (*pp).y);printf("origin is (%d,%d)n", pp->x, pp->y);struct rect r, *rp = &r;r.pt1.xrp->pt1.x(r.pt1).x(rp->pt1).x Pointers to Structures
    • Arrays of Structurestruct key { char *word; int count;};struct key keytab[NKEYS];struct key { char *word; int count;} keytab[] = { "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, "continue", 0, "default", 0, /* ... */ "unsigned", 0, "void", 0, "volatile", 0, "while", 0 };
    • /* binsearch: find word in tab[0]...tab[n-1] */int binsearch(char *word, struct key tab[], int n) { int cond; int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low + high) / 2; if ((cond = strcmp(word, tab[mid].word)) < 0) high = mid - 1; else if (cond > 0) low = mid + 1; else return mid; Binary Search } return -1;}
    • Pointers to Structuresstruct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */};struct tnode *talloc(void) { return (struct tnode *) malloc(sizeof(struct tnode));}
    • struct tnode *addtree(struct tnode *p, char *w) { int cond; if (p == NULL) { /* a new word has arrived */ p = talloc(); /* make a new node */ p->word = strdup(w); p->count = 1; p->left = p->right = NULL; } else if ((cond = strcmp(w, p->word)) == 0) p->count++; /* repeated word */ else if (cond < 0) /* less than into left subtree */ p->left = addtree(p->left, w); else /* greater than into right subtree */ p->right = addtree(p->right, w); return p;} Tree Insert
    • Dynamic Dispatch in Java translated to C
    • objects are records withfunctions as values of members
    • class BaseTest { public static void main(String[] args) { Base base1 = new Base(45);class Base { Base base2 = new Child(567, 245); Integer x; base1.print(); base2.print(); public Base(Integer v) { } x = v; } } public void print() { System.out.println("Base: " + x); }}class Child extends Base { Integer y; public Child(Integer v1, Integer v2) { super(v1); y = v2; } public void print() { System.out.println("Child: (" + x + "," + y + ")"); }} Dynamic Dispatch in Java
    • class Base { Integer x; public Base(Integer v) { x = v; } public void print() { System.out.println("Base: " + x); } } class Child extends Base { Integer y; public Child(Integer v1, Integer v2) { super(v1); y = v2;typedef struct Base { } public void print() { int x; } System.out.println("Child: (" + x + "," + y + ")");} Base; }typedef struct Child { int x; // inherited from Base int y;} Child; Representing Objects
    • typedef struct Base { int x;} Base; Defining Methodsvoid Base_print(Base* obj) { printf("Base: (%d)n", obj->x);}typedef struct Child { int x; // inherited from Base int y;} Child;void Child_print(Child* obj) { printf("Child: (%d,%d)n", obj->x, obj->y);}
    • Base* newBase(int v) { Base* obj = (Base*)malloc(sizeof(Base)); obj->x = v; return obj;}Child* newChild(int v1, int v2) { Child* obj = (Child*)malloc(sizeof(Child)); obj->x = v1; obj->y = v2; return obj;} Constructing Objects
    • class BaseTest {Dynamic Dispatch public static void main(String[] args) { Base base1 = new Base(45); Base base2 = new Child(567, 245); base1.print(); base2.print(); } }int main() { Base* base = newBase(45); Base* child = (Base*)newChild(567, 245); print(base); print(child);}void print(Base* obj) { if(<obj is a Child>) { requires reflection Child_print(obj); } else { Base_print(obj); }} not extensible
    • Virtual Method Tabletypedef struct Base { void* (**vtable)(); int x;} Base;void (*Base_Vtable[])() = { &Base_print };Base* newBase(int v) { Base* obj = (Base*)malloc(sizeof(Base)); obj->vtable = Base_Vtable; obj->x = v; return obj;}void print(Base* obj) { obj->vtable[0](obj); dynamic dispatch}
    • typedef struct Child { void* (**vtable)(); int x; // inherited from Base Subclass int y;} Child;void Child_print(Child const* obj) { printf("Child: (%d,%d)n", obj->x, obj->y);}void (*Child_Vtable[])() = { &Child_print };Child* newChild(int v1, int v2) { Child* obj = (Child*)malloc(sizeof(Child)); obj->vtable = Child_Vtable; obj->x = v1; obj->y = v2; return obj;}
    • Prototype Inheritance in JavaScript
    • objects in JavaScript are dynamically composed without class blueprints
    • var empty = {}; // An object with no propertiesvar point = { x:0, y:0 }; // Two propertiesvar point2 = { x:point.x, y:point.y+1 };// More complex valuesvar book = { Object Literals "main title" : "JavaScript", // Property names include spaces, sub-title : "The Definitive Guide", // and hyphens, so use string literals "for" : "all audiences", // for is a reserved word, so quote author : { // The value of this property is itself an object firstname : "David", surname : "Flanagan" // Note that these property names are unquoted. }};
    • var author = book.author; // Get the "author" property of the book.var name = author.surname // Get the "surname" property of the author.var title = book["main title"] // Get the "main title" property of the book.book.edition = 6; // Create an "edition" property of book.book["main title"] = "ECMAScript"; // Set the "main title" property. Querying and Setting Properties
    • Enumerating Propertiesvar o = {x:1, y:2, z:3}; // Three enumerable own propertieso.propertyIsEnumerable("toString") // => false: not enumerablefor(p in o) // Loop through the properties console.log(p); // Prints x, y, and z, but not toStringfor (p in o) { if (!o.hasOwnProperty(p)) continue; // Skip inherited properties}for (p in o) { if (typeof o[p] === "function") continue; // Skip methods}
    • /* * Copy the enumerable properties of p to o, and return o. If o and p have a * property by the same name, os property is overwritten. This function does * not handle getters and setters or copy attributes. */function extend(o, p) { for (prop in p) { // For all props in p. o[prop] = p[prop]; // Add the property to o. } return o;}
    • /* * Copy the enumerable properties of p to o, and return o. If o and p have a * property by the same name, os property is left alone. This function does not * handle getters and setters or copy attributes. */function merge(o, p) { for (prop in p) { // For all props in p. if (o.hasOwnProperty(prop)) continue; // Except those already in o. o[prop] = p[prop]; // Add the property to o. } return o;}
    • /* * Remove properties from o if there is not a property with the same name in p. * Return o. */function restrict(o, p) { for (prop in o) { // For all props in o if (!(prop in p)) delete o[prop]; // Delete if not in p } return o;}/* * For each property of p, delete the property with the same name from o. * Return o. */function subtract(o, p) { for (prop in p) { // For all props in p delete o[prop]; // Delete from o (deleting a nonexistent prop is harmless) } return o;}
    • /* * Return a new object that holds the properties of both o and p. If o and p * have properties by the same name, the values from o are used. */function union(o, p) { return merge(extend({}, o), p);}/* * Return a new object that holds only the properties of o that also appear in * p. This is something like the intersection of o and p, but the values of the * properties in p are discarded */function intersection(o, p) { return restrict(extend({}, o), p);}
    • /* * Return an array that holds the names of the enumerable own properties of o. */function keys(o) { if (typeof o !== "object") throw TypeError(); // Object argument required var result = []; // The array we will return for (var prop in o) { // For all enumerable properties if (o.hasOwnProperty(prop)) // If it is an own property result.push(prop); // add it to the array. } return result; // Return the array.
    • objects in JavaScript inheritfrom a prototype object
    • Object.create() var o1 = Object.create({x:1, y:2}); // o1 inherits properties x and y. var o2 = Object.create(null); // o2 inherits no props or methods. var o3 = Object.create(Object.prototype); // o3 is like {} or new Object().
    • var p = {x:1}; // Define a prototype object.var o = Object.create(p); // Create an object with that prototype.p.isPrototypeOf(o) // => true: o inherits from pObject.prototype.isPrototypeOf(o) // => true: p inherits from Object.prototype The prototype Attribute
    • Inheritancevar o = {} // o inherits object methods from Object.prototypeo.x = 1; // and has an own property x.var p = Object.create(o); // p inherits properties from o and Object.prototypep.y = 2; // and has an own property y.var q = Object.create(p); // q inherits properties from p, o, and Object.prototypeq.z = 3; // and has an own property z.var s = q.toString(); // toString is inherited from Object.prototypeq.x + q.y // => 3: x and y are inherited from o and p
    • Inheritance
    • var unitcircle = { r:1 }; // An object to inherit fromvar c = Object.create(unitcircle); // c inherits the property r Inheritancec.x = 1; c.y = 1; // c defines two properties of its ownc.r = 2; // c overrides its inherited propertyunitcircle.r; // => 1: the prototype object is not affected
    • How to organize code reuse?
    • function range(from, to) { var r = Object.create(range.methods); r.from = from; r.to = to; return r; Classes and Prototypes}range.methods = { includes : function(x) { return this.from <= x && x <= this.to; }, foreach : function(f) { for ( var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString : function() { return "(" + this.from + "..." + this.to + ")"; }};var r = range(1, 3); // Create a range objectr.includes(2); // => true: 2 is in the ranger.foreach(console.log); // Prints 1 2 3console.log(r); // Prints (1...3)
    • Classes and Constructorsfunction Range(from, to) { this.from = from; this.to = to;}Range.prototype = { includes : function(x) { return this.from <= x && x <= this.to; }, foreach : function(f) { for ( var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString : function() { return "(" + this.from + "..." + this.to + ")"; }};var r = new Range(1, 3); // Create a range objectr.includes(2); // => true: 2 is in the ranger.foreach(console.log); // Prints 1 2 3console.log(r); // Prints (1...3)
    • r instanceof Range// returns true if r inherits// from Range.prototype Constructors and Class Identity
    • var F = function() {}; Constructor Property // This is a function object.var p = F.prototype; // This is the prototype object associated with it.var c = p.constructor; // This is the function associated with the prototype.c === F // => true: F.prototype.constructor==F for any functionvar o = new F(); // Create an object o of class Fo.constructor === F // => true: the constructor property specifies the class
    • function Range(from, to) { this.from = from; Extend Prototype this.to = to;}Range.prototype.includes = function(x) { return this.from <= x && x <= this.to;};Range.prototype.foreach = function(f) { for ( var x = Math.ceil(this.from); x <= this.to; x++) f(x);};Range.prototype.toString = function() { return "(" + this.from + "..." + this.to + ")";};
    • Java class• instance fields• instance methods Java Style Classes in JavaScript• class fields• class methodsJavaScript• constructor object• prototype object• instance object
    • Reading & Programming in Week 4Reading Sebesta Chapter 9: Subprograms Programming in Scala Chapter 15: Case Classes and Pattern MatchingWebLab: C, JavaScript, Scala tutorials Week 5: Functional Programming