1 gentle introduction to programming session 3: higher order functions, recursion
Post on 21-Dec-2015
232 views
TRANSCRIPT
2
Admin• Sorry about the technical problems in the practical session (11-13)
• Your feedback about it?• Scala / Eclipse installation status?
3
How to Find Mistakes in Your Code• Compiler Errors• Runtime errors• What are you expected to do before contacting me
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
Review (Cont.)
• Odd’s talk (bioinformatics)• Practical session:
• Account• Linux• Interpreter / Eclipse• Understanding the compiler• Command line arguments• Homework – practice shell commands
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
Consider the Following Three Sums•1 + 2 + … + 100 = (100 * 101)/2
•1 + 4 + 9 + … + 1002 = (100 * 101 * 102)/6
•1 + 1/32 + 1/52 + … + 1/1012 ~ 2/8
In mathematics they are all captured by the notion of a sum
100
1
2
k
k
100
1k
k
101
,1
2
oddk
k
20
How Does it Work?
100
1k
k
def f1(start : Int, end : Int) : Double = {
sum((x:Int)=>x,start,(x:Int)=>x+1,end)
}
f1(1,100)
f1(50,60)
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 bdx
f
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
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
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:
37
Exercise – Power of Two
• Input: integer A
• Output: is there an integer N such that A == 2^N?
• Solution:
39
Write a program that prints an upside-down half triangle of *.
The height of the pyramid is the input.
*****
*****
****
*
Exercise – Triangle Printout
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 x0=1, the following series converges to sqrt(n):
43
Algorithm
x = 2 g = 1x/g = 2 g = ½ (1+ 2) = 1.5
x/g = 4/3 g = ½ (3/2 + 4/3) = 17/12 = 1.416666
x/g = 24/17 g = ½ (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
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
Exercise 2
Write a function that uses the formula :2/6=1/1+1/4+1/9+1/16+…+1/n2 (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
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
For next Year – toy example of a function that returns a function (to
help with the solution of ex#3)
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
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
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
RecursiveDefinition
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
56
Example - factorial
factRec(1)
factRec(2)->2*factRec (1)
factRec(3)->3*factRec (2)
main-> factRec (3)
62
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
63
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
64
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…2*…
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
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
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
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…2*1
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
Short Summary
• Design a recursive algorithm by1. Solving big instances using the solution to smaller
instances
2. Solving directly the base cases
• Recursive algorithms have1. test
2. recursive case(s)
3. base case(s)
74
Example - Modulo
• Given the following iterative version of modulo calculation
Find the recursive definition
Modulo.scala
76
Fibonacci
• “Naturally” recursive• Because the nth 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)
78
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)
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(5)
Fib(4) Fib(3)
Fib(3) Fib(2) Fib(2) Fib(1)
Fib(2)
Fib(1)
Fib(6)
Fib(4)
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
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?