1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion.

Slides:



Advertisements
Similar presentations
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Advertisements

1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Gentle Introduction to Programming Session 2: Functions.
1 Chapter 1: Introduction What you have learnt in Comp1220 or Comp1170? What will be taught in Comp 1200? - more Abstract Data Types -efficient algorithms.
Programming Recursion “To Iterate is Human, to Recurse, Divine” -- L. Peter Deutsch.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
מבוא מורחב - שיעור 2 1 Lecture 2 - Substitution Model (continued) - Recursion - Block structure and scope (if time permits)
1 Gentle Introduction to Programming Tirgul 1: Shell and Scala “hands on” in the lab.
Exercise 4 Recursion. Functions – a short reminder a group of variables and statements that is assigned a name a sub-program  inside main we can call.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
1 Gentle Introduction to Programming Session 3: Recursion.
1 Gentle Introduction to Programming Tirgul 2: Scala “hands on” in the lab.
1 Gentle Introduction to Programming Session 2: Functions.
1 Gentle Introduction to Programming Session 4: Arrays.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Fundamentals of Python: From First Programs Through Data Structures
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Recursion. Functions – reminder A function can call other functions. Return causes the execution of the function to terminate and returns a value to the.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
מבוא מורחב 1 Review: scheme language things that make up scheme programs: self-evaluating 23, "hello", #t names +, pi combinations (+ 2 3) (* pi 4) special.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion.
Principles Of Programming Languages Lecture 2 Outline Design-By-Contract Iteration vs. Recursion Scope and binding High-order procedures.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion If we have time: live demo!!!
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
1 Programming for Engineers in Python Autumn Lecture 8: Recursion.
מבוא מורחב - שיעור 5 1 Lecture 5 Higher-order procedures.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion ● Recursion or Iteration ● A Common Recursive Design Pattern ● Computing factorials ● Searching a filesystem tree ● Faster exponentiation ● Slow.
Lecture #5 מבוא מורחב.
Chapter Topics Chapter 16 discusses the following main topics:
4. Java language basics: Function
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
Lesson #6 Modular Programming and Functions.
Programming Functions.
Lesson #6 Modular Programming and Functions.
Chapter 15 Recursion.
Fibonacci Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition:
Material in the textbook on pages
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Mathematical Induction Recursion
CS21b: Structure and Interpretation
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Lesson #6 Modular Programming and Functions.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Higher-Order Procedures
Lecture #5 מבוא מורחב.
Lecture 5 Higher-order procedures מבוא מורחב - שיעור 5.
Lesson #6 Modular Programming and Functions.
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion

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

4 Today Review Higher order functions Debugger Home work review Home work Recursion

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

7 Why Functions? Why do we need functions? Code reusability Modularity Abstraction

8 Function Definition in Scala

9 Example

10 There are many ways to define functions in Scala FuncDef.scala

11 Example ((x : Int) => x * 2)(a) ((x : Int) => x * 2)(5) ((x : Int) => x * 2) 55 10

12 Today Review Higher order functions Debugger Home work review Home work Recursion

13 Closures (x : Int) => x + more // how much more? free variable

14 Closures (Cont.) What happens if we change “more”?

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 … = (100 * 101)/ … = (100 * 101 * 102)/ / /5 2 + … + 1/101 2 ~  2 /8 In mathematics they are all captured by the notion of a sum

17 In Scala Generalization:

18 The “Sum” Function

19 Usage (HigherOrderFunc.scala)

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 How Does it Work? sum += ((x:Int) => x)(i) i = ((x:Int) => x+1)(i)

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 Integration as a Function (Cont.) a b dx f

24 arctan(a) = ∫(1/(1+y 2 ))dy 0 a Integration.scala

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 Example

27 The Functions “Stack” g() ->h() f() ->g() main -> f()

28 Today Review Higher order functions Debugger Home work review Home work Recursion

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 Debugger – Add Breakpoint Right click on the desired line “Toggle Breakpoint”

31 Debugger – Start Debugging breakpoint debug

32 Debugger – Debug Perspective

33 Debugger – Debugging Current state Current location Back to Scala perspective

34 Today Review Higher order functions Debugger Home work review Home work Recursion

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 Integer Division Solution

37 Exercise – Power of Two Input: integer A Output: is there an integer N such that A == 2^N? Solution:

38 Power of Two Solution

39 Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** *** ** **** * Exercise – Triangle Printout

40 Triangle Printout Solution

41 Today Review Higher order functions Debugger Home work review Home work Recursion

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 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = x/g = 24/17g = ½ (17/ /17) = 577/408 = 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/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 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)

48 Today Review Higher order functions Debugger Home work review Home work Recursion

49 The Functions “Stack” g() ->h() f() ->g() main -> f()

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 Tower of Hanoi

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 Recursive Definition

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 Example - Factorial Termination Condition Recursive Calll Factorial.scala

56 Example - factorial factRec (1) factRec (2) ->2* factRec (1) factRec (3) ->3* factRec (2) main -> factRec (3)

57 Recursive factorial – step by step FactRec(4) n 4 Returns…

58 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*…

59 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…

60 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…

61 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 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

69 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*2

70 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*6

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 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 More Examples

74 Example - Modulo Given the following iterative version of modulo calculation Find the recursive definition Modulo.scala

75 Solution

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 Or, in Scala… Fibonacci.scala

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 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 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 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 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 Odd-Even EvenOdd.scala

84 More Home Work (Recursion)

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 Exercise 2 Given the following iterative version of sum- of-digits calculation Write the recursive definition