SlideShare a Scribd company logo
1 of 50
Download to read offline
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
  operations




data type: a collection of data values and a set
   of predefined operations on those values
type checking: the activity of ensuring that
the operands of an operation are of compatible
types.

  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 strongly
typed if type errors are always detected
        (statically or dynamically)
Boolean
Number
Integer
Float       Primitive Datatypes
Character
String
...
             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 are
called ``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.x
rp->pt1.x
(r.pt1).x
(rp->pt1).x

                              Pointers to Structures
Arrays of Structure
struct 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 Structures




struct 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 with
functions 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 Methods
void 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 Table
typedef 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 properties
var point = { x:0, y:0 }; // Two properties

var point2 = { x:point.x, y:point.y+1 };
// More complex values

var 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 Properties
var o = {x:1, y:2, z:3};
      // Three enumerable own properties

o.propertyIsEnumerable("toString")
      // => false: not enumerable

for(p in o) // Loop through the properties
  console.log(p);
  // Prints x, y, and z, but not toString

for (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, o's 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, o's 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 inherit
from 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 p

Object.prototype.isPrototypeOf(o)
   // => true: p inherits from Object.prototype




                       The prototype Attribute
Inheritance
var o = {}
    // o inherits object methods from Object.prototype
o.x = 1;
    // and has an own property x.
var p = Object.create(o);
   // p inherits properties from o and Object.prototype
p.y = 2;
   // and has an own property y.
var q = Object.create(p);
   // q inherits properties from p, o, and Object.prototype
q.z = 3;
   // and has an own property z.
var s = q.toString();
   // toString is inherited from Object.prototype
q.x + q.y
   // => 3: x and y are inherited from o and p
Inheritance
var unitcircle = { r:1 };
  // An object to inherit from

var c = Object.create(unitcircle);
  // c inherits the property r
                                          Inheritance
c.x = 1; c.y = 1;
  // c defines two properties of its own

c.r = 2;
  // c overrides its inherited property

unitcircle.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 object
r.includes(2);          // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.log(r);         // Prints (1...3)
Classes and Constructors
function 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 object
r.includes(2);           // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.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 function
var o = new F();
  // Create an object o of class F
o.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 methods
JavaScript

• constructor object
• prototype object
• instance object
Reading & Programming in Week 4

Reading

  Sebesta Chapter 9: Subprograms

  Programming in Scala Chapter 15: Case Classes
  and Pattern Matching




WebLab:
  C, JavaScript, Scala tutorials




                              Week 5: Functional Programming

More Related Content

What's hot

Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Hariz Mustafa
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Hariz Mustafa
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)Shambhavi Vats
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-conceptsraahulwasule
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseSOAT
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
oops -concepts
oops -conceptsoops -concepts
oops -conceptssinhacp
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 

What's hot (20)

Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3
 
662305 09
662305 09662305 09
662305 09
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
 
4 gouping object
4 gouping object4 gouping object
4 gouping object
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
 
Objective c
Objective cObjective c
Objective c
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

Viewers also liked

Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)lennartkats
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Eelco Visser
 
Software Language Design & Engineering
Software Language Design & EngineeringSoftware Language Design & Engineering
Software Language Design & EngineeringEelco Visser
 
Model-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive TransformationModel-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive TransformationEelco Visser
 
Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1Eelco Visser
 

Viewers also liked (6)

Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
 
Software Language Design & Engineering
Software Language Design & EngineeringSoftware Language Design & Engineering
Software Language Design & Engineering
 
Model-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive TransformationModel-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive Transformation
 
Business Ethics
Business EthicsBusiness Ethics
Business Ethics
 
Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1
 

Similar to Lecture 4: Data Types

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Scala in practice
Scala in practiceScala in practice
Scala in practicepatforna
 
Virtual function
Virtual functionVirtual function
Virtual functionharman kaur
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsMohammad Shaker
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 

Similar to Lecture 4: Data Types (20)

Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
Virtual function
Virtual functionVirtual function
Virtual function
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
class and objects
class and objectsclass and objects
class and objects
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 

More from Eelco Visser

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesEelco Visser
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingEelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionEelco Visser
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesEelco Visser
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with StatixEelco Visser
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Eelco Visser
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementEelco Visser
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersEelco Visser
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationEelco Visser
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesEelco Visser
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksEelco Visser
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisEelco Visser
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingEelco Visser
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingEelco Visser
 

More from Eelco Visser (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone Frameworks
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Lecture 4: Data Types

  • 1. Lecture 4: Data Types TI1220 2012-2013 Concepts of Programming Languages Eelco Visser / TU Delft
  • 2. Outline Type systems Structures in C Dynamic dispatch in Java Prototype inheritance in JavaScript Functional objects in Scala
  • 4. type Bool x, y; x && y x || y !x operations data type: a collection of data values and a set of predefined operations on those values
  • 5. type checking: the activity of ensuring that the operands of an operation are of compatible types. 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.
  • 6. 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
  • 7. a programming language is strongly typed if type errors are always detected (statically or dynamically)
  • 8. Boolean Number Integer Float Primitive Datatypes Character String ... Read Sebasta Chapter 6
  • 9. 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.
  • 11. 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 are called ``records'' in some languages, notably Pascal.)
  • 12. 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; }
  • 13. 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.x rp->pt1.x (r.pt1).x (rp->pt1).x Pointers to Structures
  • 14. Arrays of Structure struct 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 };
  • 15. /* 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; }
  • 16. Pointers to Structures struct 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)); }
  • 17. 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
  • 18. Dynamic Dispatch in Java translated to C
  • 19. objects are records with functions as values of members
  • 20. 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
  • 21. 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
  • 22. typedef struct Base { int x; } Base; Defining Methods void 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); }
  • 23. 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
  • 24. 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
  • 25. Virtual Method Table typedef 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 }
  • 26. 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; }
  • 27. Prototype Inheritance in JavaScript
  • 28. objects in JavaScript are dynamically composed without class blueprints
  • 29. var empty = {}; // An object with no properties var point = { x:0, y:0 }; // Two properties var point2 = { x:point.x, y:point.y+1 }; // More complex values var 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. } };
  • 30. 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
  • 31. Enumerating Properties var o = {x:1, y:2, z:3}; // Three enumerable own properties o.propertyIsEnumerable("toString") // => false: not enumerable for(p in o) // Loop through the properties console.log(p); // Prints x, y, and z, but not toString for (p in o) { if (!o.hasOwnProperty(p)) continue; // Skip inherited properties } for (p in o) { if (typeof o[p] === "function") continue; // Skip methods }
  • 32. /* * Copy the enumerable properties of p to o, and return o. If o and p have a * property by the same name, o's 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; }
  • 33. /* * Copy the enumerable properties of p to o, and return o. If o and p have a * property by the same name, o's 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; }
  • 34. /* * 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; }
  • 35. /* * 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); }
  • 36. /* * 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.
  • 37. objects in JavaScript inherit from a prototype object
  • 38. 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().
  • 39. 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 p Object.prototype.isPrototypeOf(o) // => true: p inherits from Object.prototype The prototype Attribute
  • 40. Inheritance var o = {} // o inherits object methods from Object.prototype o.x = 1; // and has an own property x. var p = Object.create(o); // p inherits properties from o and Object.prototype p.y = 2; // and has an own property y. var q = Object.create(p); // q inherits properties from p, o, and Object.prototype q.z = 3; // and has an own property z. var s = q.toString(); // toString is inherited from Object.prototype q.x + q.y // => 3: x and y are inherited from o and p
  • 42. var unitcircle = { r:1 }; // An object to inherit from var c = Object.create(unitcircle); // c inherits the property r Inheritance c.x = 1; c.y = 1; // c defines two properties of its own c.r = 2; // c overrides its inherited property unitcircle.r; // => 1: the prototype object is not affected
  • 43. How to organize code reuse?
  • 44. 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 object r.includes(2); // => true: 2 is in the range r.foreach(console.log); // Prints 1 2 3 console.log(r); // Prints (1...3)
  • 45. Classes and Constructors function 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 object r.includes(2); // => true: 2 is in the range r.foreach(console.log); // Prints 1 2 3 console.log(r); // Prints (1...3)
  • 46. r instanceof Range // returns true if r inherits // from Range.prototype Constructors and Class Identity
  • 47. 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 function var o = new F(); // Create an object o of class F o.constructor === F // => true: the constructor property specifies the class
  • 48. 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 + ")"; };
  • 49. Java class • instance fields • instance methods Java Style Classes in JavaScript • class fields • class methods JavaScript • constructor object • prototype object • instance object
  • 50. Reading & Programming in Week 4 Reading Sebesta Chapter 9: Subprograms Programming in Scala Chapter 15: Case Classes and Pattern Matching WebLab: C, JavaScript, Scala tutorials Week 5: Functional Programming