Beruflich Dokumente
Kultur Dokumente
Concepts
Lecture 2 : Basic Concepts
CS2104
Concepts
Concepts
Scala vs C
CS2104
Scala Language
Scala Language
Conciseness
// in Java
class MyClass {
private int index;
private String name;
public MyClass(int index, String name) {
this.index = index;
this.name = name;
}
}
// in Scala:
class MyClass(index: Int, name: String)
CS2104
Scala Language
Multi-Paradigm Approach
Integrates two successful programming styles
CS2104
Scala Language
CS2104
Scala Language
passed as argument
returned as result
CS2104
Scala Language
Scala
Classes
CS2104
Scala Language
Scala Classes
Factory templates that can be instantiated to objects.
Class Parameters and Explicit Overriding
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
}
override def toString(): String
= "(" + x + ", " + y + ")";
}
CS2104
Scala Language
10
Scala Classes
Parameterised by constructor arguments.
Objects are instantiated with new command, e.g.
new Point(3,4);
CS2104
Scala Language
11
Scala Classes
A class with a single object is declared with the "object"
keyword.
This example captures an executable application with
a main method that can be directly executed.
object Classes {
def main(args: Array[String]) {
val pt = new Point(1, 2)
println(pt)
pt.move(10,10)
println(pt)
}
}
CS2104
Scala Language
12
Basic Concepts
Primitive vs User-Defined Types
Constructs and Binders
Loops vs Methods
Pure vs Impure
Strict vs Lazy Evaluation
Strong vs Weak Typing
CS2104
Concepts
13
Primitive and
User-Defined Types
CS2104
Concepts
14
Primitive Types
Built-In Types of Languages
Concepts
15
Concepts
16
Concepts
17
User-Defined Types
User can design their own types
CS2104
Concepts
18
Ordinal Types
An ordinal type is a finite enumeration of distinct values
that can be associated with positive integers.
An example in Ada is
type DAYS is (Mon,Tue,Wed,Thu,Fri,Sat,Sun)
if today>Fri then
print Hippie
else
print Oh..
Concepts
19
Ordinal Types
Scala enumeration can be done through sealed case objects.
object DaysObj {
sealed trait Days
case object Mon extends Days
case object Tue extends Days
case object Wed extends Days
case object Thu extends Days
case object Fri extends Days
case object Sat extends Days
case object Sun extends Days
val daysOfWeek = Seq(Mon,Tue,Wed,Thu,Fri,Sat,Sun)
}
Concepts
20
Ordinal Types
Non-exhaustive pattern.
def weekend (x:Days) : Boolean = x match {
case Mon | Tue | Wed => false
case Sat | Sun => true
}
Exhaustive Pattern.
def weekend (x:Days) = x match {
case Mon | Tue | Wed | Thu | Fri => false
case Sat | Sun => true
}
Concepts
21
Record Types
Record is a collection of values of possibly different
types. In C, this is implemented as structures
struct [structure_tag] {
(type id)+
} id+ ;
An example:
struct Student {
char name[20];
char matric[10];
int year;
} s1, s2 ;
CS2104
Concepts
22
CS2104
Concepts
23
s.matrix
Concepts
s.year
24
Concepts
25
CS2104
Concepts
26
The type alias DuckType can be used for any objects with at
least the walk and quack methods but could have more
methods, such as the class below.
class
def
def
def
}
CS2104
Dog {
walk { println("Dog walk") }
quack { println("Dog quacks") }
run { println("Dog runs") }
Concepts
27
Concepts
28
Pointer Type
A pointer type is meant to capture the address of an
object value. There is also a special value nil that is
not a valid address.
An example in C with pointer types are:
int count, init;
int *ptr;
ptr = &init;
count = *ptr;
count
init
ptr
CS2104
Concepts
29
Pointer Type
Pointer types are crucial for recursive data type.
An example in C is:
struct node {
int val;
struct node *next;
} list;
CS2104
Concepts
list
val
next
inf_list
val
next val
next
30
vv
next
let list:node =
new Node(3,null)
CS2104
Concepts
31
CS2104
int
float
str
Concepts
32
int
Product type
(Int , Float , String)
int
float
str
float
str
CS2104
Concepts
33
int
float
str
Concepts
34
CS2104
v2:udata
Concepts
v2:udata
35
CS2104
v2:UData
Concepts
v2:UData
36
CS2104
Concepts
37
Product Type
Record and tuples belong to product types.
A pair is the foundation of product type.
A polymorphic version is:
type Pair[A,B] = (A, B)
val v2:Pair[Int,String] = (3,"cs2104");;
CS2104
Concepts
38
Sum Type
Union, ordinals and algebraic data type belongs to
sum types.
Untyped languages essentially sums different types
together, e.g:
type univ = int | float | .. | array | object
CS2104
Concepts
39
Sum Type
Like algebraic data type, sum types are usually
tagged, as follows:
type Sum[A,B] = L(A) | R(B)
val v0 = [3;cs2104] /* error */
val v1 = [L 3; R "cs2104"]
CS2104
Concepts
40
Language Constructs
and Binders
CS2104
Concepts
41
Language Constructs
Language constructs are features used to build
programs
Statements vs Expressions
Statement executed for their effects
Expression computes a result and may have
effects too.
Statement a special case of expression
Examples of Constructs
Blocks, Conditional, Sequences,
Exceptions, Loops, Calls
CS2104
Concepts
42
option
terminals
Concepts
43
Expression
<exp> ::= <id>
| <id>(<exp>*)
| <exp> ? <exp> : <exp>
| <op> <exp> | <exp> <op>
| <exp> <op> <exp>
CS2104
Concepts
44
Binders
Binders are a special class of constructs which
declare new identifiers and their possible values.
Each binder has some lexical scope where the
identifier is visible.
Values of the binders may be either immutable or
mutable.
Examples of name binders
Local declarations
Method declaration (parameters)
Pattern-Matching
CS2104
Concepts
45
Binders (in C)
Block Declaration
scope of
local variable
{ ;
<type> <id>;
names
Method Declaration
scope of
parameters
CS2104
Concepts
46
Examples (for C)
Each name may appear only once in each block, but
the name from an inner block can shadow an
identical name from its outer block.
Example : inner i shadowed the outer i name
int main() {
int i;
i=3;
i from
outer block
{ int i;
i=4;
printf("inner i is %d\n",i);
}
printf("outer i is %d\n",i);
}
CS2104
Concepts
i from
inner block
47
Concepts
48
CS2104
Concepts
49
Concepts
50
Concepts
51
Pattern-Matching in Scala
Pattern-matching can be organized as an expression.
def height(t:Tree[A]):Int = t match {
case Leaf _
=> 1
case Node(l,r) =>
max(height l, height r) }
val h = height(Node(Leaf 1,Node(Leaf 2,Leaf 3)))
CS2104
Concepts
52
Exception
Exceptions are used to make code more robust by
signalling error scenarios that might be handled.
For example, in Java, accessing NULL pointer
triggers an exception.
CS2104
Concepts
53
Exception in Java
Exception constructs are statements in Java.
Statement throw e yields an exception
Try-catch block
try {
CS2104
Concepts
54
Exception in Scala
Exceptions are case-classes in Scala.
case class UnderAgeException(message: String)
extends Exception(message)
def buyCigarettes(customer: Customer): Cigarettes =
if (customer.age < 16)
throw UnderAgeException(s"Customer must be older
than 16 but was ${customer.age}")
else new Cigarettes
CS2104
Concepts
55
Exception in Scala
Try-catch block are expression-oriented in Scala as
opposed to statement-based in Java.
val c =
try {
buyCigarettes(c)
"Yo, here are your cancer sticks! Happy smokin'!"
} catch {
case UnderAgeException(msg) => msg
}
CS2104
Concepts
56
Loops vs Methods
CS2104
Concepts
57
Loops
Loops are efficient computational structure but
requires mutable variables. An example (in C):
int fact(int n) {
int res = 1;
while (n>0) {
res = res * n;
n--;
}
return res;
}
CS2104
Concepts
58
Recursive Methods
Can use recursive methods instead:
int fact(int n) {
if (n<=0) return 1;
else return n * fact(n-1);
}
Concepts
59
CS2104
Concepts
60
Tail-Recursive Methods
We can support tail-recursive method with an extra
accumulating parameter.
int fact(int n) {
if (n<=0) return 1;
else return factit(n,1);
}
int factit(int n, int res) {
if (n==0) return res;
else return factit(n-1,n*res);
}
Concepts
61
Concepts
62
Pure vs Impure
Features
CS2104
Concepts
63
Pure vs Impure
Pure operations (in Ocaml) do not allow variables to
be re-assigned after initial binding. These tend to be
expression-oriented.
let x = 1;;
let x = x + 1;;
(* new x *)
CS2104
Concepts
64
CS2104
Concepts
65
Concepts
66
Pure Methods
Factors to support pure methods (functions).
expression-oriented language.
CS2104
Concepts
67
Evaluation Order
CS2104
Concepts
68
Evaluation Order
Expressions are evaluated in a certain order.
Strict Evaluation
Evaluate eagerly
Evaluate left-to-right order
Lazy Evaluation
Evaluate only when needed
Create suspension (to denote unevaluated value)
Speculative Evaluation
Advanced evaluation (that may be discarded)
Support better parallelism
CS2104
Concepts
69
Example in Scala
val v1 = e1;;
val v2 = e2;;
val v3 = mn(e4,e5,e6);;
CS2104
Concepts
70
CS2104
Concepts
71
Concepts
72
CS2104
Concepts
73
CS2104
Concepts
74
Speculative Evaluation
Speculation can be used to utilize parallelism.
val v = compute1(..) in
if (v>0) then v
else {val w = compute2(..); w }
CS2104
Concepts
75
Strong vs
Weak Typing
CS2104
Concepts
76
Weakly-typed (e.g. C)
Some type errors at run-time
Uses casting
e.g. void*
CS2104
Concepts
77