SlideShare a Scribd company logo
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

PPTX
iOS Session-2
PPTX
Generics in .NET, C++ and Java
PPTX
Lecture02 class -_templatev2
PPT
Generics
PDF
C# Starter L04-Collections
PPTX
Lecture11 standard template-library
PPTX
C# Generics
iOS Session-2
Generics in .NET, C++ and Java
Lecture02 class -_templatev2
Generics
C# Starter L04-Collections
Lecture11 standard template-library
C# Generics

What's hot (20)

PPTX
Lecture05 operator overloading-and_exception_handling
PPTX
Lecture08 stacks and-queues_v3
PDF
Basic object oriented concepts (1)
PPT
Core java by a introduction sandesh sharma
PPTX
Lecture07 the linked-list_as_a_data_structure_v3
PDF
PPTX
Chapter ii(oop)
PDF
Java ppt Gandhi Ravi ([email protected])
PPT
Advanced php
PDF
Java Day-7
PDF
Lecture 5: Functional Programming
PPT
38 object-concepts (1)
PPT
38 object-concepts
PDF
4 gouping object
PDF
JAVA 8 : Migration et enjeux stratégiques en entreprise
PPT
Objective c
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PPT
oops -concepts
PDF
Java OOP Programming language (Part 3) - Class and Object
PPTX
Object Oriented JavaScript
Lecture05 operator overloading-and_exception_handling
Lecture08 stacks and-queues_v3
Basic object oriented concepts (1)
Core java by a introduction sandesh sharma
Lecture07 the linked-list_as_a_data_structure_v3
Chapter ii(oop)
Java ppt Gandhi Ravi ([email protected])
Advanced php
Java Day-7
Lecture 5: Functional Programming
38 object-concepts (1)
38 object-concepts
4 gouping object
JAVA 8 : Migration et enjeux stratégiques en entreprise
Objective c
Java Generics Introduction - Syntax Advantages and Pitfalls
oops -concepts
Java OOP Programming language (Part 3) - Class and Object
Object Oriented JavaScript
Ad

Viewers also liked (6)

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

Similar to Lecture 4: Data Types (20)

PDF
Object-oriented Basics
DOCX
Java programming lab_manual_by_rohit_jaiswar
PDF
TypeScript Introduction
PDF
Scala in practice
PPSX
What's New In C# 7
PPTX
Basic java, java collection Framework and Date Time API
PDF
Interpreter Case Study - Design Patterns
PDF
Lezione03
PDF
Lezione03
PPTX
More on Classes and Objects
PDF
Scala in practice
DOCX
Dotnet 18
DOCX
Virtual function
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
PPTX
class and objects
PDF
C# Starter L02-Classes and Objects
PDF
Mattbrenner
PDF
Kotlin Developer Starter in Android projects
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Introduction to c#
Object-oriented Basics
Java programming lab_manual_by_rohit_jaiswar
TypeScript Introduction
Scala in practice
What's New In C# 7
Basic java, java collection Framework and Date Time API
Interpreter Case Study - Design Patterns
Lezione03
Lezione03
More on Classes and Objects
Scala in practice
Dotnet 18
Virtual function
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
class and objects
C# Starter L02-Classes and Objects
Mattbrenner
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Introduction to c#

More from Eelco Visser (20)

PDF
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
PDF
CS4200 2019 | Lecture 4 | Syntactic Services
PDF
CS4200 2019 | Lecture 3 | Parsing
PDF
CS4200 2019 | Lecture 2 | syntax-definition
PDF
CS4200 2019 Lecture 1: Introduction
PDF
A Direct Semantics of Declarative Disambiguation Rules
PDF
Declarative Type System Specification with Statix
PDF
Compiler Construction | Lecture 17 | Beyond Compiler Construction
PDF
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
PDF
Compiler Construction | Lecture 15 | Memory Management
PDF
Compiler Construction | Lecture 14 | Interpreters
PDF
Compiler Construction | Lecture 13 | Code Generation
PDF
Compiler Construction | Lecture 12 | Virtual Machines
PDF
Compiler Construction | Lecture 11 | Monotone Frameworks
PDF
Compiler Construction | Lecture 10 | Data-Flow Analysis
PDF
Compiler Construction | Lecture 9 | Constraint Resolution
PDF
Compiler Construction | Lecture 8 | Type Constraints
PDF
Compiler Construction | Lecture 7 | Type Checking
PDF
Compiler Construction | Lecture 6 | Introduction to Static Analysis
PDF
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 Lecture 1: Introduction
A Direct Semantics of Declarative Disambiguation Rules
Declarative Type System Specification with Statix
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 5 | Transformation by Term Rewriting

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Cloud computing and distributed systems.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
cuic standard and advanced reporting.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
sap open course for s4hana steps from ECC to s4
Cloud computing and distributed systems.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
cuic standard and advanced reporting.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

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