Lecture 5
Lecture 5
2-2
Constructions
2-3
Example: Java object constructions
▪ Assume:
class Date {
public int m, d;
public Date (int m, int d) {
this.m = m; this.d = d;
}
…
}
▪ Object constructions:
Date today = new Date(12, 25);
Date tomorrow =
new Date(today.m, today.d+1);
2-4
Example: Ada record and array
constructions
▪ Record constructions:
type Date is record
m: Month;
d: Day_Number;
end record;
today: Date := (Dec, 25);
tomorrow: Date := (today.m, today.d+1);
▪ Array construction:
leap: Integer range 0 .. 1;
…
month_length: array (Month) of Integer :=
(31, 28+leap, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31);
2-5
Example: Haskell tuple and list constructions
▪ Tuple constructions:
today = (Dec, 25)
m, d = today
tomorrow = (m, d+1)
▪ List construction:
monthLengths =
[31, if isLeap y then 29 else 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
2-6
Function calls (1)
2-8
Function calls (3)
2-9
Conditional expressions
2-10
Example: Java if-expressions
▪ Java if-expression:
x>y ? x : y
2-11
Example: Haskell if- and case-expressions
▪ Haskell if-expression:
if x>y then x else y
▪ Haskell case-expression:
case m of
feb -> if isLeap y then 29 else 28
apr -> 30
jun -> 30
sep -> 30
nov -> 30
_ -> 31
2-12
Implementation notes
2-13
Representation of primitive types (1)
2-14
Representation of primitive types (2)
2-18
Representation of arrays (2)
2-19
Representation of objects (simplified)
▪ Example (Java):
class Point {
Point tag
private float x, y;
… // methods 1.0 x
}
Circle tag 2.0 y
class Circle
extends Point { 0.0 x
private float r; Rect. tag y
… // methods 0.0
} 1.5 x
5.0 r
class Rectangle 2.0 y
extends Point {
private float w, h; 3.0 w
… // methods
} 4.0 h
2-20
Representation of disjoint unions (1)
2-21
Representation of disjoint unions (2)
▪ Example (Ada):
type Accuracy is (exact, inexact);
type Number (acc: Accuracy := exact) is
record
case acc of
when exact => ival: Integer;
when inexact => rval: Float;
end case;
end record;
acc exact acc inexact
ival 2 rval 3.1416
2-22
Representation of disjoint unions (3)
▪ Example (Ada):
type Form is (pointy,circular,rectangular);
type Figure (f: Form := pointy) is record
x, y: Float;
case f is
when pointy => null;
when circular => r: Float;
when rectangular => w, h: Float;
end case; f pointy f circ. f rect.
end record;
x 1.0 x 0.0 x 1.5
2-24
Representation of recursive types (1)
2 3 5 7 data
tail
2-25
Representation of recursive types (2)
▪ Example (Haskell):
data IntList = Nil | Cons Int IntList
2-26
Representation of recursive types (3)
▪ Example (Java):
class IntList {
public int data;
public IntList tail;
…
}
2-27