Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Similar documents
Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Module 05: Types of recursion

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

CS116 - Module 5 - Accumulative Recursion

Module 9: Binary trees

CS115 - Module 10 - General Trees

How to Design Programs

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Trees. Binary arithmetic expressions. Visualizing binary arithmetic expressions. ((2 6) + (5 2))/(5 3) can be defined in terms of two smaller

Module 10: General trees

Trees. Readings: HtDP, sections 14, 15, 16.

Module 8: Binary trees

CS115 - Module 9 - filter, map, and friends

Trees. Example: Binary expression trees. Example: Evolution trees. Readings: HtDP, sections 14, 15, 16.

Module 8: Local and functional abstraction

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

Graphs. Directed graphs. Readings: Section 28

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Assignment: 7. Due: Language level: Allowed recursion:

CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local. CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local 1

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

Repetition Through Recursion

Scheme Quick Reference

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer

Module 9: Trees. If you have not already, make sure you. Read How to Design Programs Sections 14, 15, CS 115 Module 9: Trees

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer

Introduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD

CS115 - Module 4 - Compound data: structures

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

Lecture 10: Recursion vs Iteration

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

Local defini1ons. Func1on mul1ples- of

YOUR NAME PLEASE: *** SOLUTIONS ***

Recursion I and II. Discrete Structures (CS 173) Madhusudan Parthasarathy, University of Illinois 1

Scheme Quick Reference

Recursive Functions. Biostatistics 615 Lecture 5

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

CS 320: Concepts of Programming Languages

CS 5010 Program Design Paradigms Lesson 6.1

Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 4.1

Solving Your Problem by Generalization

CS 115 Lecture Notes Winter 2019

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

q To develop recursive methods for recursive mathematical functions ( ).

Functional Programming. Pure Functional Programming

q To develop recursive methods for recursive mathematical functions ( ).

Getting to places from my house...

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Hints for Exercise 4: Recursion

Style and Submission Guide

ormap, andmap, and filter

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

CS 1101 Exam 3 A-Term 2013

Module 10: Imperative Programming, Modularization, and The Future

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

Module 2: Classical Algorithm Design Techniques

CS2500 Exam 2 Fall 2011

CSCE 110: Programming I

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

More About Recursive Data Types

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

CS/CE 2336 Computer Science II

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

Tail Recursion and Accumulators

The files IList.java, MTList.java, and ConsList.java that define a generic cons-list that implements the Traversal interface.

CSCC24 Functional Programming Scheme Part 2

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

UCT Algorithm Circle: Number Theory

t 1 =2 t n =3t n 1 1,n 1

6.001 Notes: Section 8.1

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK

(add1 3) 4 (check-expect (add1 3) 4)

Introduction to Scheme

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

Macros & Streams Spring 2018 Discussion 9: April 11, Macros

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Introduction to OCaml

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

Algorithm Design: GCD

Names and Functions. Chapter 2

COMP Lecture Notes Iterative and Recursive Procedures for Strings

Transcription:

Types of recursion Readings: none. In this module: learn to use accumulative recursion learn to recognize generative recursion CS 135 Fall 2018 07: Types of recursion 1 Structural vs. general recursion All of the recursion we have done to date has been structural. The templates we have been using have been derived from a data definition and specify the form of the recursive application. In this module we will learn how to use a new form of recursion, accumulative recursion. We ll also learn to recognize generative recursion. For the next several lecture modules we will use (primarily) structural recursion and accumulative recursion. We will avoid generative recursion until the end of the course. CS 135 Fall 2018 07: Types of recursion 2 Pure structural recursion Recall from Module 05: In pure structural recursion, all arguments to the recursive function application (or applications, if there are more than one) are either: unchanged, or one step closer to a base case according to the data definition CS 135 Fall 2018 07: Types of recursion 3

The limits of structural recursion ;; (max-list lon) produces the maximum element of lon ;; max-list: (listof Num) Num ;; requires: lon is nonempty (define (max-list lon) (cond [(empty? (rest lon)) (first lon)] [(> (first lon) (max-list (rest lon))) (first lon)] [else (max-list (rest lon))])) There may be two recursive applications of max-list. CS 135 Fall 2018 07: Types of recursion 4 The code for max-list is correct. But computing (max-list (countup-to 1 25)) is very slow. Why? The initial application is on a list of length 25. There are two recursive applications on the rest of this list, which is of length 24. Each of those makes two recursive applications. CS 135 Fall 2018 07: Types of recursion 5 list-max 25 24 24 23 23 23 23........................ CS 135 Fall 2018 07: Types of recursion 6

Intuitively, we can find the maximum of a list of numbers by scanning it, remembering the largest value seen so far. Computationally, we can pass down that largest value seen so far as a parameter called an accumulator. This parameter accumulates the result of prior computation, and is used to compute the final answer that is produced in the base case. This approach results in the code on the next slide. CS 135 Fall 2018 07: Types of recursion 7 ;; (max-list/acc lon max-so-far) produces the largest ;; of the maximum element of lon and max-so-far ;; max-list/acc: (listof Num) Num Num (define (max-list/acc lon max-so-far) (cond [(empty? lon) max-so-far] [(> (first lon) max-so-far) (max-list/acc (rest lon) (first lon))] [else (max-list/acc (rest lon) max-so-far)])) CS 135 Fall 2018 07: Types of recursion 8 (define (max-list2 lon) (max-list/acc (rest lon) (first lon))) Now even (max-list2 (countup-to 1 2000)) is fast. (max-list2 (cons 1 (cons 2 (cons 3 (cons 4 empty))))) (max-list/acc (cons 2 (cons 3 (cons 4 empty))) 1) (max-list/acc (cons 3 (cons 4 empty)) 2) (max-list/acc (cons 4 empty) 3) (max-list/acc empty 4) 4 CS 135 Fall 2018 07: Types of recursion 9

This technique is known as structural recursion with an accumulator, or sometimes just accumulative recursion. It is more difficult to develop and reason about such code, which is why purely structural recursion is preferable if it is appropriate. HtDP discusses it much later than we are doing (after material we cover in lecture module 10) but in more depth. CS 135 Fall 2018 07: Types of recursion 10 Structural vs. accumulative recursion In pure structural recursion, all arguments to the recursive function application (or applications, if more than one) are either: unchanged, or one step closer to a base case in the data definition In structural recursion with an accumulator, arguments are as above, plus one or more accumulators containing partial answers. The accumulatively recursive function is a helper function, and a wrapper function sets the initial value of the accumulator(s). CS 135 Fall 2018 07: Types of recursion 11 Another example: reversing a list ;; my-reverse: (listof Any) (listof Any) (define (my-reverse lst) ; using pure structural recursion (cond [(empty? lst) empty] [else (append (my-reverse (rest lst)) (list (first lst)))])) Intuitively, append does too much work in repeatedly moving over the produced list to add one element at the end. This has the same worst-case behaviour as insertion sort. CS 135 Fall 2018 07: Types of recursion 12

Reversing a list with an accumulator (define (my-reverse lst) ; primary function (my-rev/acc lst empty)) (define (my-rev/acc lst acc) ; helper function (cond [(empty? lst) acc] [else (my-rev/acc (rest lst) (cons (first lst) acc))])) CS 135 Fall 2018 07: Types of recursion 13 A condensed trace (my-reverse (cons 1 (cons 2 (cons 3 empty)))) (my-rev/acc (cons 1 (cons 2 (cons 3 empty))) empty) (my-rev/acc (cons 2 (cons 3 empty)) (cons 1 empty)) (my-rev/acc (cons 3 empty) (cons 2 (cons 1 empty))) (my-rev/acc empty (cons 3 (cons 2 (cons 1 empty)))) (cons 3 (cons 2 (cons 1 empty))) CS 135 Fall 2018 07: Types of recursion 14 Example: greatest common divisor In Math 135, you learn that the Euclidean algorithm for GCD can be derived from the following identity for m > 0: gcd(n, m) = gcd(m, n mod m) We also have gcd(n, 0) = n. We can turn this reasoning directly into a Racket function. CS 135 Fall 2018 07: Types of recursion 15

;; (euclid-gcd n m) computes gcd(n,m) using Euclidean algorithm ;; euclid-gcd: Nat Nat Nat (define (euclid-gcd n m) (cond [(zero? m) n] [else (euclid-gcd m (remainder n m))])) This function does not use structural or accumulative recursion. CS 135 Fall 2018 07: Types of recursion 16 The arguments in the recursive application were generated by doing a computation on m and n. The function euclid-gcd uses generative recursion. Once again, functions using generative recursion are easier to get wrong, harder to debug, and harder to reason about. We will return to generative recursion in a later lecture module. Avoid generative recursion until then. CS 135 Fall 2018 07: Types of recursion 17 Structural vs. accumulative vs. generative recursion In (pure) structural recursion, all arguments to the recursive function application (or applications, if there are more than one) are either unchanged, or one step closer to a base case in the data definition. In accumulative recursion, parameters are as above, plus parameters containing partial answers used in the base case. In generative recursion, parameters are freely calculated at each step. (Watch out for correctness and termination!) CS 135 Fall 2018 07: Types of recursion 18

Goals of this module You should be able to recognize uses of pure structural recursion, accumulative recursion, and generative recursion. You should be able to write functions using accumulative recursion. CS 135 Fall 2018 07: Types of recursion 19