Top Banner
1 Gentle Introduction to Programming Session 6: Lists, Course Summary
94

1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

1

Gentle Introduction to Programming

Session 6: Lists, Course Summary

Page 2: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

2

Review• Sorting, searching and time-complexity analysis • Scala memory model• Guest lecture by Prof. Ronitt Rubinfeld• Object-oriented programming (OOP)

• Classes and Objects• Functional Objects (Rational Numbers example)

Page 3: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

3

Todayהפתעה! (+ משובים) •• Finish Functional Objects• Guest lecture by Prof. Ronitt Rubinfeld 10:10 • Course Summary ++• Lists• More OOP (inheritance, hierarchy, polymorphism)

• Go home!

Page 4: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

4

Object-Oriented Programming (OOP)

• Represent problem-domain entities using a computer language

• When building a software in a specific domain, describe the different components of the domain as types and variables

• Thus we can take another step up in abstraction

Page 5: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

5

Class as a BlueprintA class is a blueprint of objects

Page 7: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

7

Rational Numbers

• A ration number is a number that can be expressed as a ration n/d (n,d integers, d not 0)

• Examples: 1/2, 2/3, 112/239, 2/1

• Not an approximation

Page 8: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

8

Specification• Add, subtract, multiply, divide

• println should work smoothly• Immutable (result of an operation is a new rational number)

• It should feel like native language support

Page 9: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

9

Constructing a Rational

• How client programmer will create a new Rational object?

Class parameters

Page 10: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

10

Constructing a Rational• The Scala compiler will compile any code placed in

the class body, which isn’t part of a field or a method definition, into the primary constructor

?

Page 11: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

11

Reimplementing toString

• toString method• A more useful implementation of toString would

print out the values of the Rational’s numerator and denominator

• override the default implementation

Page 12: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

12

Usage

• Now we can remove the debug println…

Page 13: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

13

Checking Preconditions

• Ensure the data is valid when the object is constructed

• Use require

Page 14: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

14

Define “add” Method

• Immutable• Define add:

Page 15: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

15

Add Fields• n, d are in scope in the add method• Access then only on the object on which add

was invoked

Page 16: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

16

Test Add, Access Fields

Page 17: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

17

Self Reference (this)

• Define method lessThan:

• Define method max:

Page 18: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

18

Auxiliary Constructors• Constructors other then the primary

• Example: a rational number with a denominator of 1 (e.g., 5/1 5)

• We would like to do: new Rational(5)• Auxiliary constructor first action: invoke

another constructor of the same class

• The primary constructor is thus the single point of entry of a class

Page 19: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

19

Revised Rational

Page 20: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

20

Private Fields and Methods

• 66/42 = 11/7• To normalize divide the numerator and

denominator by their greatest common divisor (gcd)• gcd(66,42) = 6 (66/6)/(42/6) = 11/7• No need for Rational clients to be aware of this• Encapsulation

Page 21: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

21

Off Topic: Calculate gcd• gcd(a,b) = g

• a = n * g• b = m * g• gcd(n,m)=1(otherwise g is not the gcd)• a = t * b + r = t * m * g + r g is a divisor of r

• gcd(a,b) = gcd(b,a%b)• The Euclidean algorithm: repeat iteratively:

if (b == 0) return aelse repeat using a b, b a%b

• http://en.wikipedia.org/wiki/Euclidean_algorithm

Page 22: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

22

Correctness• Example:

gcd(40,24) gcd(24,16) gcd(16,8) gcd(8,0) 8

• Prove: g = gcd(a,b) = gcd(b,a%b)= g1• g1 is a divisor of a ( g1 ≤ g)• There is no larger divisor of a ( g1 ≥ g)

• ≤ : a = t * b + r a = t * h * g1 + v * g1 g1 is a divisor of a

• ≥ : assume g > g1 a = t * b + r g is a divisor of b and r contradiction

Page 23: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

23

Implementation

Page 24: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

24

Revised Rational

Page 25: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

25

Defining Operators• Why not use natural arithmetic operators?

• Replace add by the usual mathematical symbol

• Operator precedence will be kept

• All operations are method calls

Page 26: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

26

Revised Rational

Page 27: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

27

Usage

Page 28: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

28

Method Overloading• Now we can add and multiply rational numbers!• What about mixed arithmetic?

• r * 2 won’t work • r * new Rational(2) is not nice

• Add new methods for mixed addition and multiplication

• Method overloading• The compiler picks the correct overloaded

method

Page 29: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

29

Usage

• The * method invoked is determined in each case by the type of the right operand

Page 30: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

30

Revised Rational

Page 31: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

31

Implicit Conversions

• 2 * r 2.*(r) method call on 2 (Int) Int class contains no multiplication method that takes a Rational argument

• Create an implicit conversion that automatically converts integers to rational numbers when needed

Page 32: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

32

Companion Object

Page 33: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

33

Revised Rational

• Define implicit conversion in Rational.scala, after defining object Rational

Page 34: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

34

In Eclipse

• In Rational.scala:• Companion object

(object Rational)• Rational class (class

Rational)

• Place the main method in another file

Page 35: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

35

Summary• Customize classes so that they are natural

to use• fields, methods, primary constructor• Method overriding• Self reference (this)• Define several constructors• Encapsulation• Define operators as method• Method overloading• Implicit conversions, companion object

Page 36: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

36

Complete HomeWork• Implement class Complex so it is natural to use

complex numbers• Examples:

Page 37: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

37

Todayהפתעה! )+ משובים( •• Finish Functional Objects• Guest lecture by Prof. Ronitt Rubinfeld 10:10 • Course Summary ++• Lists• More OOP (inheritance, hierarchy, polymorphism)

• Go home!

Page 38: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

38

Course Description

This course will provide a gentle introduction to programming

using Scala for highly motivated students with little or no prior experience in programming

Page 39: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

39

Objective

Bridge the gap for students without prior programming knowledge

Page 40: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

40

Course Description

Lectures will be interactive featuring in-class exercises with lots of support

You are expected to work hard!

Page 41: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

41

Course PlanSession Material

1 Basic concepts in CS and programming, basic Scala

2 Basic Scala (cont.), Functions

3 Recursion

4 Arrays

5 Sort, Complexity, Object Oriented Programming

6 Summary, Lists, more OOP

Page 42: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

42

Why Scala?

• Semester A: Scheme• Semester B: Java• Scala language has some features similar to

Scheme and some to Java• Scala is cool!

Page 43: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

43

Summary

• General introduction to CS and programming• Basic Scala• Development tools:

• Interpreter• Eclipse (+ debugger)

• Compiler, Interpreter

Page 44: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

44

Compiler

Page 45: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

45

Interpreter

Page 46: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

46

How it works in Scala

Page 47: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

47

Higher Order Functions

101

,1

2

oddk

k

100

1k

k

100

1

2

k

k

Page 49: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

49

Recursion and Efficiency

• The recursive form, however elegant, may be much less efficient

• The number of redundant calls grow exponentially!

Fib(5)

Fib(4) Fib(3)

Fib(3) Fib(2) Fib(2) Fib(1)

Fib(2)

Fib(1)

Fib(6)

Fib(4)

Page 50: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

50

Recursive Vs. Iterative Process

Operation pending

No pending operations

Page 51: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

51

“Tail” Recursion in Scala

• Scala compiler translate tail-recursion to iterative execution

• Thus, the functions-stack is not growing

Page 52: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

52

Arrays

• Array: sequential block of memory that holds variables of the same type

• Array can be declared for any type

• The array variable itself holds the address in memory of beginning of sequence

• foreach, filter, map,…

0 1 2 3 4 5 6 7 8 9

s

……

Page 53: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

53

Arrays - Example

Page 54: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

54

Stack, Queue

• Stack – מחסנית• Applications: Function’s stack• Implementation ideas

• Queue – תור, First In First Out (FIFO)• Applications: Scheduling, typing• Implementation idea• Cyclic Queue

Page 55: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

55

Binary Search• Input:

• A sorted array of integers A• An integer query q

• Output:• The index of q in A if q is a member of A• -1 otherwise

• Algorithm:• Check the middle element of A• If it is equal to q, return its index• If it is >= q, search for q in A[0,…,middle-1]• If it is < q, search for q in A[middle+1,...,end]

Page 56: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

56

Time Complexity of BS• Worst case analysis

• Size of the inspected array:

n n/2 n/4 ….. 1

• Each step is very fast (a small constant number of operations)

• There are log2(n) such steps

• So it takes ~ log2(n) steps per search

• Much faster then ~ n

Page 57: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

57

Bubble Sort Time ComplexityArray of size n

n iterationsi iterations

constant

(n-1 + n-2 + n-3 + …. + 1) * const ~ ½ * n2

Page 58: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

58

Marge Sort• If the array is of length 0 or 1, then it is already sorted. Otherwise:

• Divide the unsorted array into two sub-arrays of about half the size

• Sort each sub-array recursively by re-applying merge sort

• Merge the two sub-arrays back into one sorted array

n + 2 * (n/2) + 22 * n/22 + 23 * n/23 + … + 2log(n) * n/2log(n) =

n + n + … + n = n * log(n)

log(n)

Page 59: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

59

Bucket Sort• Linear-time sorting algorithm! • But: restrictions on data – bounded

integers…

Page 60: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

60

Quick Sort

• Want to hear about it?

• http://en.wikipedia.org/wiki/Quicksort

Page 61: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

61

Scala Memory Model

• Passing arguments to functions, local names

• Objects in memory

• Stack, Heap, Garbage collection

Page 62: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

62

Object-Oriented Programming

• Represent problem-domain entities using a computer language

• Abstraction

• Classes as blueprint / data-types• Scala API (and Java’s)

Page 63: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

63

Rational Numbers Example• Customize classes so that they are natural

to use• fields, methods, primary constructor• Method overriding• Self reference (this)• Define several constructors• Encapsulation• Define operators as method• Method overloading• Implicit conversions, companion object

Page 64: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

64

Guest Lectures

• (soon to be Dr.) Ohad Barzilay• Oded Magger• Prof. Benny Chor• Prof. Ronitt Rubinfeld

Page 65: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

65

Todayהפתעה! )+ משובים( •• Finish Functional Objects• Guest lecture by Prof. Ronitt Rubinfeld 10:10 • Course Summary ++• Lists• More OOP (inheritance, hierarchy, polymorphism)

• Go home!

Page 66: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

66

Programming in Scala

Chapter 16: Working with Lists Chapter 22: Implementing Lists

Page 67: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

67

Problems with Arrays

• Limited in space (static): the size of an array is defined as it is created

• Costly to perform dynamic operations (e.g., add an element)

Page 68: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

68

Linked Lists• Built out of links, each link holds:

• Data• Pointer to the next link (tail)

• Pointer to the first element (head)

Page 69: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

69

Linked Lists (cont.)• Infinite loop? (linklinklink….)

• Nil – the empty list

• The elements have the same type

Page 70: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

70

Lists Vs. Arrays

List Array

Initialization / memory

Economical Wasteful

Insert element Fast Slow

Remove element Fast Slow

Direct access No direct access Direct access

Traverse Linear Linear

Page 71: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

71

Functionality• initiate

• isEmpty

• length

• add element

• remove element

• append

• reverse

Page 72: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

72

Lists in Scala• List class have a type parameter T (similar

to Arrays…)•

• List operations are based on three basic methods:• isEmpty : Boolean – true iff the list is empty• head : T – first element in list• tail : List[T] – a list consisting of the elements

except the first

Page 73: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

73

Initiating Lists

Page 74: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

74

Constructing Lists• All lists are build from two fundamental

building blocks:• Nil• :: (cons)

Page 75: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

75

Example: Insertion Sort

Page 76: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

76

Implementation of ::

Page 77: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

77

Implementation of: length, map

Page 78: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

78

Concatenating Lists

Page 79: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

79

Reverse a List

def rev[T](xs : List[T]) = {

if (xs.isEmpty)

xs

else

rev(xs.tail):::List(xs.head)

}

Complexity?

Page 80: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

80

Higher Order Methods

• map• filter• partition• foreach• And more

Page 81: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

81

Example - map

map(_+1) map((x:Int)=>x+1)

Page 82: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

82

Example – filter, partition

Page 83: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

83

Example – filter, partition

Page 84: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

84

Example – foreach

Page 85: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

85

Example – sort

Page 86: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

86

Other Data Structures• Trees• Maps

Page 87: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

87

Example

var capital = Map( "US" "Washington", "France" "paris", "Japan" "tokyo" )

capital += ( "Russia" "Moskow" )

for ( (country, city) capital ) capital += ( country city.capitalize )

assert ( capital("Japan") == "Tokyo" )

Page 88: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

88

Pattern Matching in Scala

Here's a a set of definitions describing binary trees:

And here's an inorder traversal of binary trees:

This design keeps• purity: all cases are classes or objects• extensibility: you can define more cases elsewhere• encapsulation: only parameters of case classes are revealed

abstract class Tree[T]

case object Empty extends Tree

case class Binary(elem: T, left: Tree[T], right: Tree[T]) extends Tree

def inOrder [T] ( t: Tree[T] ): List[T] = t match { case Empty => List() case Binary(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r)}

The case modifier of an object or class means you can pattern match on it

Page 89: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

89

Todayהפתעה! )+ משובים( •• Finish Functional Objects• Guest lecture by Prof. Ronitt Rubinfeld 10:10 • Course Summary ++• Lists• More OOP (inheritance, hierarchy, polymorphism)

• Go home!

Page 90: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

90

More OOP (only talking…)

• Inheritance

• Class Hierarchy

• Polymorphism

Page 91: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

91

Scala Hierarchy

Page 92: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

92

Todayהפתעה! )+ משובים( •• Finish Functional Objects• Guest lecture by Prof. Ronitt Rubinfeld 10:10 • Course Summary ++• Lists• More OOP )inheritance, hierarchy, polymorphism(

• Go home!

Page 93: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

93

Thanks / References• Guest lecturers: Ohad, Oded, Benny,

Amiram, Ronitt

• Administration: Avia, Pnina

• System: Ami, Eitan, Boaz, Eddie

• Initiator: Dr. Lior Wolf

• References:• “Programming in Scala”• Jackie Assa• Scheme Course• Don’t remember

Page 94: 1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

94

חג שמח!תהנו משארית

החופשה!