Download presentation
Presentation is loading. Please wait.
1
1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion
2
2 Admin Sorry about the technical problems in the practical session (11-13) Your feedback about it? Scala / Eclipse installation status?
3
3 How to Find Mistakes in Your Code Compiler Errors Runtime errors What are you expected to do before contacting me
4
4 Today Review Higher order functions Debugger Home work review Home work Recursion
5
5 Review More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Functions Why do we need them Types: methods, local (nested), literal, valu
6
6 Review (Cont.) Odd’s talk (bioinformatics) Practical session: Account Linux Interpreter / Eclipse Understanding the compiler Command line arguments Homework – practice shell commands
7
7 Why Functions? Why do we need functions? Code reusability Modularity Abstraction
8
8 Function Definition in Scala
9
9 Example
10
10 There are many ways to define functions in Scala FuncDef.scala
11
11 Example ((x : Int) => x * 2)(a) ((x : Int) => x * 2)(5) ((x : Int) => x * 2) 55 10
12
12 Today Review Higher order functions Debugger Home work review Home work Recursion
13
13 Closures (x : Int) => x + more // how much more? free variable
14
14 Closures (Cont.) What happens if we change “more”?
15
15 Can procedures get and return procedures? In Scala a function can: Return a function as its return value, Receive functions as arguments. Why is this useful?
16
16 Consider the Following Three Sums 1 + 2 + … + 100 = (100 * 101)/2 1 + 4 + 9 + … + 100 2 = (100 * 101 * 102)/6 1 + 1/3 2 + 1/5 2 + … + 1/101 2 ~ 2 /8 In mathematics they are all captured by the notion of a sum
17
17 In Scala Generalization:
18
18 The “Sum” Function
19
19 Usage (HigherOrderFunc.scala)
20
20 How Does it Work? def f1(start : Int, end : Int) : Double = { sum((x:Int)=>x,start,(x:Int)=>x+1,end) } f1(1,100) f1(50,60)
21
21 How Does it Work? sum += ((x:Int) => x)(i) i = ((x:Int) => x+1)(i)
22
22 Integration as a Function Integration under a curve f is approximated by dx ( f(a) + f(a + dx) + f(a + 2dx) + … + f(b) ) a b dx f
23
23 Integration as a Function (Cont.) a b dx f
24
24 arctan(a) = ∫(1/(1+y 2 ))dy 0 a Integration.scala
25
25 Function as a Contract If the operands have the specified types, the procedure will result in a value of the specified type otherwise, its behavior is undefined (maybe an error, maybe random behavior) A contract between the caller and the procedure. Caller responsible for argument number and types function responsible to deliver correct result
26
26 Example
27
27 The Functions “Stack” g() ->h() f() ->g() main -> f()
28
28 Today Review Higher order functions Debugger Home work review Home work Recursion
29
29 The Debugger Some programs may compile correctly, yet not produce the desirable results These programs are valid and correct Scala programs, yet not the programs we meant to write! The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program
30
30 Debugger – Add Breakpoint Right click on the desired line “Toggle Breakpoint”
31
31 Debugger – Start Debugging breakpoint debug
32
32 Debugger – Debug Perspective
33
33 Debugger – Debugging Current state Current location Back to Scala perspective
34
34 Today Review Higher order functions Debugger Home work review Home work Recursion
35
35 Exercise – Integer Division Input: Two integers – A and B Output: How many times A contains B (it is the result of the integer division A/B) Do not use the operators ‘/’, ‘*’ Solution:
36
36 Integer Division Solution
37
37 Exercise – Power of Two Input: integer A Output: is there an integer N such that A == 2^N? Solution:
38
38 Power of Two Solution
39
39 Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** *** ** **** * Exercise – Triangle Printout
40
40 Triangle Printout Solution
41
41 Today Review Higher order functions Debugger Home work review Home work Recursion
42
42 Approximating Square Root Given integer x > 0, how to find an approximation of x? Newton was the first to notice that for any positive n, and when x 0 =1, the following series converges to sqrt(n):
43
43 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = 1.416666 x/g = 24/17g = ½ (17/12 + 24/17) = 577/408 = 1.4142156 Algorithm: Make a guess g Improve the guess by averaging g, x/g Keep improving the guess until it is good enough Example: calculate the square root of 2
44
44 Exercise 1 Write a program that receives from the user: An integer x > 0 A double representing the approximation’s accuracy Calculates an approximation of x within the required accuracy Use the function Math.abs(x) which returns the absolute value of x
45
45 Exercise 2 Write a function that uses the formula : 2 /6=1/1+1/4+1/9+1/16+…+1/n 2 (where n goes to infinity) in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of Write a program that gets an integer n from the user, and approximate using n terms of the above formula Use a nested function sum, with signature:
46
46 Exercise 3 Write a function deriv : Input: a function f (Double=>Double), accuracy dx Output: function df (Double=>Double), the derivative of f. df (x) = (f(x+dx) – f(x))/dx Define a few simple functions (linear, square) and calculate their derivative at various points received by command line arguments
47
47 For next Year – toy example of a function that returns a function (to help with the solution of ex#3)
48
48 Today Review Higher order functions Debugger Home work review Home work Recursion
49
49 The Functions “Stack” g() ->h() f() ->g() main -> f()
50
50 Recursive Functions How to create a process of unbounded length? Needed to solve more complicated problems Tower of Hanoi Start with a simple example
51
51 Tower of Hanoi
52
52 Tower of Hanoi How to solve for arbitrary number of disks n ? Let’s name the pegs: source, target, spare All n disks are initially placed on source peg Solution: 1.Move n-1 upper disks from source to spare 2.More lower (bigger) disk from source to target 3.Move n-1 disks from spare to target (smaller. Easier?) Base condition: a single disk
53
53 Factorial As we saw, n! = 1*2*3*… *(n-1)*n Thus, we can also define factorial the following way: 0! = 1 n! = n*(n-1)! for n>0 (n-1)! * n Recursive Definition
54
54 A Recursive Definition Functions can also call themselves! However, usually not with the same parameters Some functions can be defined using smaller occurrences of themselves Every recursive function has a “termination condition”. The function stops calling itself when it is satisfied
55
55 Example - Factorial Termination Condition Recursive Calll Factorial.scala
56
56 Example - factorial factRec (1) factRec (2) ->2* factRec (1) factRec (3) ->3* factRec (2) main -> factRec (3)
57
57 Recursive factorial – step by step FactRec(4) n 4 Returns…
58
58 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*…
59
59 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…
60
60 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…
61
61 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*…
62
62 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…
63
63 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…
64
64 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*…
65
65 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns…
66
66 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns…
67
67 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns… 1
68
68 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*1
69
69 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*2
70
70 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*6
71
71 General Form of Recursive Algorithms Base case: small (non-decomposable) problem Recursive case: larger (decomposable) problem At least one base case, and at least one recursive case. test + base case recursive case
72
72 Short Summary Design a recursive algorithm by 1. Solving big instances using the solution to smaller instances 2. Solving directly the base cases Recursive algorithms have 1. test 2. recursive case(s) 3. base case(s)
73
73 More Examples
74
74 Example - Modulo Given the following iterative version of modulo calculation Find the recursive definition Modulo.scala
75
75 Solution
76
76 Fibonacci “Naturally” recursive Because the n th term is the sum of the (n-1) th and (n-2) th terms Therefore, the recursive definition is: fib(1) = 0 ; fib(2) = 1 /* base */ fib(n) = fib(n-1) + fib(n-2)
77
77 Or, in Scala… Fibonacci.scala
78
78 Recursion and Efficiency The recursive form, however elegant, may be much less efficient The number of redundant calls grow exponentially! Fib(6) Fib(4)
79
79 Efficient Recursive Fibonacci Pass the values that were already calculated to the recursive function This technique is called Memoization How would we keep the values that were already calculated? Fib(6) Fib(4)
80
80 Fibonacci with Memoization int main(void) { int fib[SIZE],n,i; fib[1] = 0; fib[2] = 1; for (i = 3; i < SIZE; ++i) fib[i] = -1; printf("Please enter a non-negative number\n"); scanf("%d",&n); printf("fib(%d) = %d\n",n,fib_rec_mem(n,fib)); return 0; }
81
81 Fibonacci with Memoization int fib_rec_mem(int n,int fib[]) { if (fib[n] != -1) return fib[n]; fib[n] = fib_rec_mem(n-1,fib) + fib_rec_mem(n-2,fib); return fib[n]; }
82
82 Odd-Even Given a function ‘odd(n : Int) : Boolean’ Return true on n that are odd, false on even n Write a function ‘even(n : Int) : Boolean’ that: Return true on n that are even, false on odd n This is easy
83
83 Odd-Even EvenOdd.scala
84
84 More Home Work (Recursion)
85
85 Exercise 1 Write a program that receives two non- negative integers and computes their product recursively Hint: Notice that the product a*b is actually a+a+…+a (b times). How does this help us define the problem recursively?
86
86 Exercise 2 Given the following iterative version of sum- of-digits calculation Write the recursive definition
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.