100% found this document useful (1 vote)
18 views75 pages

Data Types Handout1

Uploaded by

Sơn Đặng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
18 views75 pages

Data Types Handout1

Uploaded by

Sơn Đặng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Data Types

Dr. Nguyen Hua Phung

HCMC University of Technology, Viet Nam

09, 2014

Dr. Nguyen Hua Phung Data Types 1 / 78


Outline

1 Scalar Types
Built-in Types
User-Defined Ordinal Types
2 Composite Types
Array Types
String Types
Record Types
Union Types
Set Types
Pointer and Reference Types
Recursive Type
3 Type Checking

Dr. Nguyen Hua Phung Data Types 2 / 78


Introduction

A data type is
a homogeneous collection of values and
a set of operations which manipulate these values
Uses of type system:
Conceptual organization
Error detection
Implementation

Dr. Nguyen Hua Phung Data Types 3 / 78


Type System

A type system consists of:


The set of predefined types
The mechanisms to define a new type
The mechanisms for the control of types:
Type equivalence
Type compatibility
Type inference
The specification which type constraints are statically
or dynamically checked

Dr. Nguyen Hua Phung Data Types 4 / 78


Scalar Types

Scalar Types are


atomic
used to compose another types
sometimes supported directly by hardware
booleans, characters, integers, floating-point,
fixed-point, complex, void, enumerations, intervals,...
Skip Scalar Types

Dr. Nguyen Hua Phung Data Types 6 / 78


Integer

Languages may support several sizes of integer


Java’s signed integer sizes: byte, short, int, long
Some languages include unsigned integers
Supported directly by hardware: a string of bits
To represent negative numbers: two’s complement

Dr. Nguyen Hua Phung Data Types 7 / 78


Floating-Point

Model real numbers, but only as approximations


Languages for scientific use support at least two
floating-point types (e.g., float and double)
Precision and range
IEEE Floating-Point Standard 754

Dr. Nguyen Hua Phung Data Types 8 / 78


IEEE-754

Sign bit 8 bits 23 bits

S Exponent Fraction
Single precision

11 bits 52 bits

S Exponent Fraction
Double precision

Dr. Nguyen Hua Phung Data Types 9 / 78


Decimal

For business applications (money)


Essential to COBOL
C#offers a decimal data type
Store a fixed number of decimal digits
Advantage: accuracy
Disadvantage: limited range, wastes memory

Dr. Nguyen Hua Phung Data Types 10 / 78


Boolean

Simplest of all
Range of values: two elements, one for “true” and
one for “false”
Could be implemented as bits, but often as bytes

Dr. Nguyen Hua Phung Data Types 11 / 78


Character

Stored as numeric codings


Most commonly used coding: ASCII
An alternative, 16-bit coding: Unicode
Includes characters from most natural languages
Originally used in Java
C# and JavaScript also support Unicode

Dr. Nguyen Hua Phung Data Types 12 / 78


User-Defined Ordinal Types

An ordinal type is one in which the range of possible


values can be easily associated with the set of
positive integers
Examples of primitive ordinal types in Java
integer
char
boolean

Dr. Nguyen Hua Phung Data Types 13 / 78


Enumeration Types

All possible values, which are named constants, are


provided in the definition
C# example
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
days myDay = Mon, yourDay = Tue;
Design issues:
Is an enumeration constant allowed to appear in more
than one type definition?
Are enumeration values coerced to integer?
Are any other types coerced to an enumeration type?

Dr. Nguyen Hua Phung Data Types 14 / 78


Enumeration Type (2)

Readability
no need to code a color as a number
Reliability
operations (don’t allow colors to be added)
No enumeration variable can be assigned a value
outside its defined range
Better support for enumeration than C++:
enumeration type variables are not coerced into
integer types
Implemented as integers

Dr. Nguyen Hua Phung Data Types 15 / 78


Subrange Type

an ordered contiguous subsequence of an ordinal


type
type pos = 0 .. MAXINT;
Subrange types behave as their parent types; can be
used as for variables and array indices
type sv = array[1 .. 50] of string;
Subrange types are the parent types with code
inserted (by the compiler) to restrict assignments to
subrange variables

Dr. Nguyen Hua Phung Data Types 16 / 78


Composite Types

An object in composite type contains many


components which can be accessed individually
component’s type may be the same (homogeneous)
or different (heterogeneous)
the number of components may be fixed or changed
there may be operations on structured-type object or
its components
there may be component insertion/removal
operations
there may be creation/destruction operations

Dr. Nguyen Hua Phung Data Types 18 / 78


Array Types

Collection of homogeneous data elements


Each element is identified by its position relative to
the first element and referenced using subscript
expression
array_name (index expression list) → an element
What type are legal for subscripts?
Pascal, Ada: any ordinal type (integer, boolean, char,
enumeration)
Others: subrange of integers
Are subscripting expressions range checked?
Most contemporary languages do not specify range
checking but Java, ML, C#
Unusual case: Perl
Skip Array Type

Dr. Nguyen Hua Phung Data Types 19 / 78


Subscript Binding and Array Categories

Static
static int x[10];
Fixed Stack-dynamic
int x[10]; //inside a function
Stack-dynamic
cin »n;
int x[n];
Fixed Heap-dynamic
int[] x = new int[10];
Heap-dynamic
cin »n;
int[] x = new int[n];

Dr. Nguyen Hua Phung Data Types 20 / 78


Array Initialization

Some language allow initialization at the time of


storage allocation
C, C++, Java, C# example
int list [] = {4, 5, 7, 83}
Character strings in C and C++
char name [] = "freddie";
Arrays of strings in C and C++
char *names [] = {"Bob", "Jake", "Joe"};
Java initialization of String objects
String[] names = {"Bob", "Jake", "Joe"};

Dr. Nguyen Hua Phung Data Types 21 / 78


Rectangular and Jagged Arrays

C, C++, Java, C#: jagged arrays


myArray[3][7]
Fortran, Ada, C#: rectangular array
myArray[3,7]

rectangular jagged

Dr. Nguyen Hua Phung Data Types 22 / 78


Slices

A slice is some substructure of an array; nothing


more than a referencing mechanism
Slices are only useful in languages that have array
operations
E.g. Python
vector = [2, 4, 6, 8, 10, 12, 14, 16]
mat = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
vector[3:6], mat[1], mat[0][0:2]

Dr. Nguyen Hua Phung Data Types 23 / 78


Implementation of Arrays

Access function maps subscript expressions to an


address in the array
Single-dimensioned: list of adjacent memory cells
Access function for single-dimensioned arrays:
address(list[k]) = address(list[lower_bound]) +
((k-lower_bound) * element_size)

Dr. Nguyen Hua Phung Data Types 24 / 78


Accessing Two-dimensional Arrays

a[0,0] a[0,0]

a[0,1] a[1,0]

a[0,2] a[2,0]

a[1,0] a[0,1]

a[1,1] a[1,1]

a[1,2] a[2,1]

Row-major order Column-major order


used in most languages used in Fortran

Dr. Nguyen Hua Phung Data Types 25 / 78


Accessing Two-dimensional Arrays

Row-major order:
Location (a[i,j]) = α + (((i - row_lb) * n) + (j - col_lb)) * E
where α is address of a[row_lb,col_lb] and E is element
size

1 2 . . . j-1 j . . . n
1
2
..
.
i-1
N
i
..
.
m

Dr. Nguyen Hua Phung Data Types 26 / 78


Compile-time Descriptors

Multidimensional array
Element type
Array Index type
Element type Number of dimensions
Index range 1
Index type
..
Index lower bound .
Index upper bound Index range n
Address Address
Single dimensional array Multi-dimensional array

Dr. Nguyen Hua Phung Data Types 27 / 78


Associative Arrays

An associative array is an unordered collection of


data elements that are indexed by an equal number
of values called keys
For example,
dt = [("name","John");("age","28");("address","1 John st.")]
dt["name"] ⇒ "John"
dt["address"] ⇒ "1 John st."
User defined keys must be stored
Similar to Map in Scala
Design issues: What is the form of references to
elements

Dr. Nguyen Hua Phung Data Types 28 / 78


String Types

Values are sequences of characters


Design issues:
Is it a primitive type or just a special kind of array?
Should the length of strings be static or dynamic?
Typical operations
Assignment
Comparison (=, >, etc.)
Concatenation
Substring reference
Pattern matching (regular expression)
Skip String Type

Dr. Nguyen Hua Phung Data Types 29 / 78


String Length Options

Static: String length is fixed at compiling time


Python, Java String class
compile-time descriptor
Limited Dynamic: String length may be changed but
less than a limit
C, C++
run-time descriptor
Dynamic: String length may be changed without any
limit
Perl, JavaScript
run-time descriptor; linked list
Ada supports all three string length options

Dr. Nguyen Hua Phung Data Types 30 / 78


Descriptor

Limited dynamic string


Static string Maximum length
String length Current length
Address Address
Compile-time descriptor Run-time descriptor
for static length strings for limited dynamic length
strings

Dr. Nguyen Hua Phung Data Types 31 / 78


Record Types

A record:
heterogeneous aggregate of data elements
individual elements are identified by names
Popular in most languages, OO languages use
objects as records
Design issues:
What is the syntactic form of references to the field?
Are elliptical references allowed
Skip Record Type

Dr. Nguyen Hua Phung Data Types 32 / 78


Definition of Records in Ada

Record structures are indicated in an orthogonal way


type Emp_Name_Type is record
First: String (1..20);
Mid: String (1..10);
Last: String (1..20);
end record;
type Emp_Rec_Type is record
Emp_Name: Emp_Name_Type;
Hourly_Rate: Float;
end record;
Emp_Rec: Emp_Rec_Type;

Dr. Nguyen Hua Phung Data Types 33 / 78


References to Records

Notation:
Dot-notation: Emp_Rec.Emp_Name.Mid
Keyword-based:
Mid OF Emp_Name OF Emp_Rec
Format:
Fully qualified references: include all record names
Elliptical references: may leave out some record
names as long as reference is unambiguous
Mid, Mid OF Emp_Name, Mid OF Emp_Rec

Dr. Nguyen Hua Phung Data Types 34 / 78


Operations in Records

Assignment is very common if the types are identical


Ada allows record comparison
Ada records can be initialized with aggregate literals
COBOL provides MOVE CORRESPONDING
Copies fields which have the same name

Dr. Nguyen Hua Phung Data Types 35 / 78


Evaluation

Straight forward and safe design


Comparison of arrays and records
Arrays Records
homogenous heterogeneous
elements are pro- elements are pro-
cessed in the same cessed in different
way way
dynamic subscripting static subscripting

Dr. Nguyen Hua Phung Data Types 36 / 78


Implementation of Record Type

Record
Name
Type Field 1
Offset
.. ..
. .
Name
Type Field n
Offset
Address

Dr. Nguyen Hua Phung Data Types 37 / 78


Data Alignment

b-byte aligned
A b-byte aligned object has an address that is a multiple
of b bytes.

Example
1 A char (one byte) will be 1-byte aligned.
2 A short (two bytes) will be 2-byte aligned.
3 A int (four bytes) will be 4-byte aligned.
4 A long (four bytes) will be 4-byte aligned.
5 A float (four bytes) will be 4-byte aligned.

Dr. Nguyen Hua Phung Data Types 38 / 78


Data structure Padding

Padding
when a structure member is
followed by a member with a larger alignment
requirement, or
at the end of the structure to make the structure size
be multiple of the biggest member size.

struct MyStruct {
char data1;
int data2;
char data3;
short data4;
char data5;
};
What is the size of the above struct?
Dr. Nguyen Hua Phung Data Types 39 / 78
Union Types

A union is a type whose variables are allowed to


store different type values at different times during
execution
type Shape is (Circle, Triangle, Rectangle);
type Colors is (Red, Green, Blue);
type Figure (Form: Shape) is record
Filled: Boolean;
Color: Colors;
case Form is
when Circle => Diameter: Float;
when Triangle =>
Leftside, Rightside: Integer;
Angle: Float;
when Rectangle => Side1, Side2: Integer;
end case;
end record;
Skip Union Type

Dr. Nguyen Hua Phung Data Types 40 / 78


Ada Union Type Illustrated

rectangle: side1, side2

circle: diameter

triangle: leftside, rightside, angle


Discriminant(form)
color
filled

Dr. Nguyen Hua Phung Data Types 41 / 78


Design issues

Should type checking be required?


Discriminated vs. Free Union
Fortran, C, and C++ provide union constructs in
which there is no language support for type checking;
the union in these languages is called free union
Type checking of unions require that each union
include a type indicator called a discriminant
Supported by Ada
Should unions be embedded in records?

Dr. Nguyen Hua Phung Data Types 42 / 78


Example

union { x.bt[0] x.bt[1]


i n t data ;
char b t [ 2 ] ; 12 7A
} x;
x . data = 0x7A12 ; x.data
c o u t << x . b t [ 0 ] << e n d l ; / / 18
c o u t << x . b t [ 1 ] << e n d l ; / / 122

Dr. Nguyen Hua Phung Data Types 43 / 78


Evaluation of Unions

Potentially unsafe construct in some languages


Do not allow type checking
Java and C# do not support unions
Reflective of growing concerns for safety in
programming language

Dr. Nguyen Hua Phung Data Types 44 / 78


Set Types

x : set of 1 . . 1 0 ;
y : set of char ;

represent the concept of set


has operators: membership, union, intersection,
different,...
implemented by bit chain or hash table.

Dr. Nguyen Hua Phung Data Types 45 / 78


Pointer Types

int *ptr;

A pointer type variable has a range of values that


consists of memory addresses and a special value,
nil
Provide the power of indirect addressing
Provide a way to manage dynamic memory
A pointer can be used to access a location in the area
where storage is dynamically created (usually called a
heap)
Skip Pointer Type

Dr. Nguyen Hua Phung Data Types 46 / 78


Pointer Operations

Two fundamental operations: assignment and


dereferencing
Assignment is used to set a pointer variable’s value to
some useful address
int *p,*q;
p=q
Dereferencing yields the value stored at the location
represented by the pointer’s value
Dereferencing can be explicit or implicit
C++ uses an explicit operation via *
j = *ptr
sets j to the value located at ptr

Dr. Nguyen Hua Phung Data Types 47 / 78


Pointer Deferencing Illustrated

7080
An anonymous
206 dynamic variable

ptr 7080

j 206

The deferencing operation j = *ptr

Dr. Nguyen Hua Phung Data Types 48 / 78


Problems with Pointers

Dangling pointers (dangerous)


A pointer points to a heap-dynamic variable that has
been de-allocated
Lost heap-dynamic variable
An allocated heap-dynamic variable that is no longer
accessible to the user program (often called garbage)

Dr. Nguyen Hua Phung Data Types 49 / 78


Pointers in C and C++

int ∗ ptr ;
i n t count , i n i t ;
...
ptr = &i n i t ;
count = ∗ p t r ;

Extremely flexible but must be used with care


Pointers can point at any variable regardless of when
it was allocated
Used for dynamic storage management and
addressing

Dr. Nguyen Hua Phung Data Types 50 / 78


Pointers in C and C++

Pointer arithmetic is possible


int l i s t [10]; int ∗ ptr ; ptr = l i s t ;
∗( p t r + 1)
∗( p t r + index )
p t r [ index ]
Explicit dereferencing and address-of operators
Domain type need not be fixed (void *)
void * can point to any type and can be type checked
(cannot be de-referenced)

Dr. Nguyen Hua Phung Data Types 51 / 78


Pointer Operations

Pointer points to a record in C/C++


Explicit: (*p).name
Implicit: p -> name
Management of heap use explicit allocation
C: function malloc
C++: new and delete operators

Dr. Nguyen Hua Phung Data Types 52 / 78


Design Issues of Pointers

What are the scope of and lifetime of a pointer


variable?
What is the lifetime of a heap-dynamic variable?
Are pointers restricted as to the type of value to which
they can point?
Are pointers used for dynamic storage management,
indirect addressing, or both?
Should the language support pointer types, reference
types, or both?

Dr. Nguyen Hua Phung Data Types 53 / 78


Reference Types

int A;
i n t &rA = A ;
A = 1;
cout << rA << endl ;
rA ++;
cout << A << endl

Pointers refer to an address, references refer to


object or value
C++ includes a special kind of pointer type called a
reference type that is used primarily for formal
parameters
Java extends C++’s reference variables and allows
them to replace pointers entirely
C# includes both the references of Java and the
pointers of C++
Dr. Nguyen Hua Phung Data Types 54 / 78
References vs. Pointers in C++

Reference Type Pointer


i n t A; i n t A;
i n t & rA = A ; i n t ∗ pA = &A ;
rA ⇒ A *pA ⇒ A
N/A pA++
cannot reseated pA = &B
cannot be null pA = null
cannot be uninitialized int* pA

Dr. Nguyen Hua Phung Data Types 55 / 78


Evaluation of Pointers

Dangling pointers and garbage are big problems


Pointers are like goto’s–they widen the range of cells
that can be accessed by a variable
Essential in some kinds of programming applications,
e.g. device drivers
Using references provide some of the flexibility and
capabilities of pointers, without the hazards

Dr. Nguyen Hua Phung Data Types 56 / 78


Representations of Pointers

Most computers use single values


Intel microprocessors use segment and offset

Dr. Nguyen Hua Phung Data Types 57 / 78


Dangling Pointer Problem

Tombstone: extra heap cell that is a pointer to the


heap-dynamic variable
The actual pointer variable points only at tombstones
When heap-dynamic variable de-allocated,
tombstone remains but set to nil
Costly in time and space
Locks-and-keys: Pointer values are represented as
(key, address) pairs
Heap-dynamic variables are represented as variable
plus cell for integer lock value
When heap-dynamic variable allocated, lock value is
created and placed in lock cell and key cell of pointer

Dr. Nguyen Hua Phung Data Types 58 / 78


Blank

Dr. Nguyen Hua Phung Data Types 59 / 78


Recursive Type

A value of a recursive type can contain a (reference to)


value of the same type.
type i n t _ l i s t = { i n t v a l ;
i n t _ l i s t next ; }
{3 ,{43 ,{ −1 ,{6 , n u l l } } } }

type c h a r _ t r e e = { char v a l ;
char_tree l e f t ;
char_tree r i g h t ; }
{ A , { B , { C, n u l l , n u l l } , { D , { E , n u l l , n u l l } , n u l l } } ,
{F, null , n u l l } }

Dr. Nguyen Hua Phung Data Types 60 / 78


Example on Ocaml

type c h a r _ b t r e e =
Tree of char ∗ c h a r _ b t r e e ∗ c h a r _ b t r e e
| Null

Tree ( ’ A ’ , Tree ( ’ B ’ , Tree ( ’ C’ , N u l l , N u l l ) ,


Tree ( ’ D’ ,
Tree ( ’ E ’ , N u l l , N u l l ) ,
Null )) ,
Tree ( ’ F ’ , N u l l , N u l l ) )

type ’ a b t r e e = Tree of ’ a ∗ ’ a b t r e e ∗ ’ a b t r e e
| Null

Tree ( 4 , Tree ( 3 , N u l l , N u l l ) , Tree ( 6 , N u l l , N u l l ) )

Dr. Nguyen Hua Phung Data Types 61 / 78


Type Expression: Motivation Example

x : array [ 1 . . 1 0 ] of record
a : array [ 5 . . 1 0 ] of i n t e g e r ;
b : record
c : real ;
d : array [ 1 . . 3 ] of r e a l ;
end ;
d: string [3];
end ;

Dr. Nguyen Hua Phung Data Types 63 / 78


Type Expressions

A basic type is a type expression.


boolean, char, integer, float, void, subrange.
A type name is a type expression.
A type constructor applied to type expressions is a
type expression. Including:
Arrays: array(I,T) where I: index type, T:element type
Products: T1 × T2
Records: record((name1 × T1) × (name2 × T2) ×. . . )
Pointers: pointer(T)
Functions: T1 → T2
A type variable is a type expression.

Dr. Nguyen Hua Phung Data Types 64 / 78


Example

int ⇒ int
typedef int siso; ⇒ siso
int t[10]; ⇒ array(0..9,int)
int foo(int a,float b) ⇒ (int × float) → int
struct int a;int b ⇒ record((a × int) × (b × int))
int *p ⇒ pointer(int)
template <class T> struct vd T a; T b[3];
⇒ record((a × T) × (b × array(0..2,T)))

Dr. Nguyen Hua Phung Data Types 65 / 78


Type Checking

Definition
Type checking is the activity of ensuring that a program
respects the rules imposed by the type system

Static type checking is performed in compiling


time. It is often applied for static type binding
languages.
Dynamic type checking is performed in running
time. It is often applied for
dynamic type binding languages
dome features in static type binding language that
cannot be type checked during compiling time.

Dr. Nguyen Hua Phung Data Types 66 / 78


Type Inference

Definition
Type inference is the ability of a compiler to deduce type
information of program unit.

Example on Scala
def add(x:Int) = x + 1
Return type of function add is inferred to be Int

Mechanism
Assign type (built-in or variable type)to leaf nodes in
AST.
Generate type constraints in each internal node in
AST.
Resolve these type constraints

Dr. Nguyen Hua Phung Data Types 67 / 78


Type Equivalence

an operand of one type can be substituted for one of


the other type without coercion.
Two approaches:
Equivalence by name: same type name
type C e l s i u s = F l o a t ;
type F a h r e n h e i t = F l o a t ;
Structural equivalence: same structure
type A = record type B = record
f i e l d 1 : integer ; f i e l d 1 : integer ;
f i e l d 2 : real ; f i e l d 2 : real ;
end end

Dr. Nguyen Hua Phung Data Types 68 / 78


Static Type Checking for Structural Equivalence

function s e q u i v ( Type s , Type t ) : boolean


begin
i f ( s and t are t h e same b a s i c type ) then
return true ;
else i f ( s = array ( s1 , s2 ) and t = array ( t1 , t 2 ) then
r e t u r n s e q u i v ( s1 , t 1 ) and s e q u i v ( s2 , t 2 ) ;
else i f ( s = s1 × s2 and t = t 1 × t 2 ) then
r e t u r n s e q u i v ( s1 , t 1 ) and s e q u i v ( s2 , t 2 ) ;
else i f ( s = p o i n t e r ( s1 ) and t = p o i n t e r ( t 1 ) ) then
r e t u r n s e q u i v ( s1 , t 1 ) ;
else i f ( s = s1 → s2 and t = t 1 → t 2 ) then
r e t u r n s e q u i v ( s1 , t 1 ) ;
else
return false ;

Dr. Nguyen Hua Phung Data Types 69 / 78


Type Compatibility

Definition
Type T is compatible with type S if a value of type T is
permitted in any context where a value of type S is
admissible
Example, int and float
A type T is compatible with type S when:
T is equivalence to S
Values of T form a subset of values of S
All operations on S are permitted on T
Values of T correspond in a canonical fashion to
values of S. (int and float)
Values of T can transform to some values of S.

Dr. Nguyen Hua Phung Data Types 70 / 78


Type Conversion

Definition
Type conversion is conversing a value of this type to a
value of another type

Implicit conversion - coercion


Explicit conversion - cast

Dr. Nguyen Hua Phung Data Types 71 / 78


Polymorphism

Definition
Monomorphic: any language object has a unique type
Polymorphic: the same object can have more than
one type

Example, +: int × int → int or float × float → float


Kind of Polymorphism
Ad hoc polymorphism - Overloading
Universal Polymorphism
Parametric polymorphism (swap(T& x,T& y))
Subtyping polymorphism (in OOP)

Dr. Nguyen Hua Phung Data Types 72 / 78


Example of Parametric Polymorphism

template <typename T>


void swap ( T& x , T& y ) {
T tmp = x ;
x = y;
y = tmp ;
}
int a = 5 , b = 3;
swap ( a , b ) ;
c o u t << a << " " << b << e n d l ;

Dr. Nguyen Hua Phung Data Types 73 / 78


Example of Subtyping Polymorphism

class Polygon
public :
v i r t u a l f l o a t getArea ( ) = 0 ;
class Rectangle : public Polygon
public :
f l o a t getArea ( )
return height ∗ width ;
private :
f l o a t height , width ;
class T r i a n g l e : public Polygon
public :
f l o a t getArea ( )
float p = (a + b + c ) / 2;
r e t u r n s q r t ( p ∗ ( p−a ) ∗ ( p−b ) ∗ ( p−c ) ) ;
private :
float a,b, c ;
Shape ∗ s ;
s = ( . . . ) ? new Rectangle ( 3 , 4 ) : new T r i a n g l e ( 3 , 4 , 5 ) ;
s−>getArea ( ) ;
Dr. Nguyen Hua Phung Data Types 74 / 78
Example on Scala

a b s t r a c t class Stack [ A ]
def push ( x : A ) : Stack [ A ] =
new NonEmptyStack [ A ] ( x , t h i s )
def isEmpty : Boolean
def t o p : A
def pop : Stack [ A ]
class EmptyStack [ A ] extends Stack [ A ]
def isEmpty = t r u e
def t o p = e r r o r ( " EmptyStack . t o p " )
def pop = e r r o r ( " EmptyStack . pop " )
class NonEmptyStack [ A ] ( elem : A , r e s t : Stack [ A ] )
extends Stack [ A ]
def isEmpty = f a l s e
def t o p = elem
def pop = r e s t
v a l x = new EmptyStack [ I n t ]
v a l y = x . push ( 1 ) . push ( 2 )
p r i n t l n ( y . pop . t o p )

Dr. Nguyen Hua Phung Data Types 75 / 78


Example on Scala

def i s P r e f i x [ A ] ( p : Stack [ A ] , s : Stack [ A ] ) : Boolean = {


p . isEmpty | |
p . t o p == s . t o p && i s P r e f i x [ A ] ( p . pop , s . pop )
}

Dr. Nguyen Hua Phung Data Types 76 / 78


Summary [1]

Type system is mainly used to error detection


Primitive type
Structure type
Type checking

Dr. Nguyen Hua Phung Data Types 77 / 78


References

Maurizio Gabbrielli and Simone Martini, Programming


Languages: Principles and Paradigms, Chapter 8, Springer,
2010.

Dr. Nguyen Hua Phung Data Types 78 / 78

You might also like