CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

Similar documents
Module 05: Types of recursion

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Recursive Definitions

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

CS116 - Module 5 - Accumulative Recursion

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

RECURSION, RECURSION, (TREE) RECURSION! 2

CSI33 Data Structures

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Data Structures And Algorithms

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

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

TAIL CALLS, ITERATORS, AND GENERATORS 11

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

RECURSION, RECURSION, (TREE) RECURSION! 3

Comp215: More Recursion

Recursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!

recursive algorithms 1

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

TAIL RECURSION, SCOPE, AND PROJECT 4 11

ENVIRONMENT DIAGRAMS AND RECURSION 2

Algorithm Design and Recursion. Search and Sort Algorithms

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

RECURSION, RECURSION, (TREE) RECURSION! 3

Object-Oriented Programming and Design D0010E. Interactive lecture 2. Overview of the lecture. Writing larger classes Documentation Recursion

Problem Set CVO 103, Spring 2018

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

Programming for Engineers in Python

CS1 Lecture 15 Feb. 19, 2018

Recursive Functions. Biostatistics 615 Lecture 5

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Koch snowflake. Fractal Fern

Reduction & Recursion Overview

A Concepts-Focused Introduction to Functional Programming Using Standard ML Sample Exam #1 Draft of August 12, 2010

Declarative concurrency. March 3, 2014

Topic 5: Examples and higher-order functions

CSE 230 Intermediate Programming in C and C++ Recursion

RECURSION. Problem Solving with Computers-II 6

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Chapter 6 Recursion. The Concept of Recursion

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

CS 310 Advanced Data Structures and Algorithms

CSCI 121: Recursive Functions & Procedures

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

ITERATION AND RECURSION 3

CS1 Recitation. Week 2

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

UNIT 5A Recursion: Basics. Recursion

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

CSE 143 Lecture 10. Recursion

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

ENVIRONMENT DIAGRAMS AND RECURSION 2

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

Principles of Programming Languages

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

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Measuring Efficiency

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Recall from Last Time: Big-Oh Notation

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

Recursion & Iteration

Lecture 7 CS2110 Fall 2014 RECURSION

Recursion vs Induction

Reading 8 : Recursion

Lecture 6 CS2110 Spring 2013 RECURSION

15 212: Principles of Programming. Some Notes on Induction

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

RECURSION: n. SEE RECURSION 3

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate.

Lecture 35: Analysis Review & Tail Recursion 10:00 AM, Nov 28, 2018

Lecture 10: Recursion vs Iteration

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

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

6.001 Recitation 23: Register Machines and Stack Frames

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

INTERPRETERS AND TAIL CALLS 9

Streams and Evalutation Strategies

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

Homework 3 COSE212, Fall 2018


Decorators in Python

BBM 201 DATA STRUCTURES

Goals: Define computational problem instance of a computational problem algorithm pseudocode Briefly discuss recursive procedure big-o notation

CS 61B Discussion Quiz 1. Questions

CS205: Scalable Software Systems

Transcription:

CSE 341 Lecture 5 efficiency issues; tail recursion; print Ullman 3.3-3.4; 4.1 slides created by Marty Stepp http://www.cs.washington.edu/341/

Efficiency exercise Write a function called reverse that accepts a list and produces the same elements in the opposite order. reverse([6, 2, 9, 7])produces [7,9,2,6] Write a function called rangethat accepts a maximum integer value nand produces the list [1, 2, 3,..., n-1, n]. Produce an empty list for all numbers less than 1. Example: range(5) produces [1,2,3,4,5] 2

Flawed solutions These solutions are correct; but they have a problem... fun reverse([]) = [] reverse(first :: rest) = reverse(rest) @ [first]; fun range(0) = [] range(n) = range(n - 1) @ [n]; 3

Efficiency of the @ operator val x = [2, 4, 7]; val y = [5, 3]; val a = 9 :: x; val z = x @ y; a 9 x 2 4 7 y 5 3 z 2 4 7 The ::operator is fast: O(1) simply creates a link from the first element to front of right The @operator is slow: O(n) must walk/copy the left list and then append the right one using @in a recursive function ntimes : function is O(n 2 ) 4

Flawed solution in action fun reverse([]) = [] reverse(first :: rest) = reverse(rest) @ [first]; reverse([2, 4, 7, 6]); 6 7 4 @ first 2 rest 4 7 6 6 7 @ first 4 rest 7 6 6 @ first 7 rest 6 [] @ first 6 rest [] 5

Fixing inefficient reverse How can we improve the inefficient reverse code? fun reverse([]) = [] reverse(first :: rest) = reverse(rest) @ [first]; Hint:Replace @with ::as much as possible. ::adds to the front of a list. How can we perform a reversal by repeatedly adding to the front of a list? (Think iteratively...) 6

Better reverse solution fun reverse([]) = [] reverse(l) let (* lst accumulates reversed values *) fun helper(lst, []) = lst helper(lst, first::rest) = helper(first::lst, rest) in helper([], L) end; The parameter lst here serves as an accumulator. 7

Fixing inefficient range How can we improve the inefficient rangecode? fun range(0) = [] range(n) = range(n - 1) @ [n]; Hint:Replace @with ::as much as possible. Hint:We can't build the list from front to back the way it's currently written, because n(the max of the range) is the only value we have available. Hint:Consider a helper function that can build a range in order from smallest to largest value. 8

Better range solution fun range(n) = let fun helper(lst, i) = if i = 0 then lst else helper(i :: lst, i - 1) in helper([], n) end; The parameter lst here serves as an accumulator. 9

Times-two function Consider the following function: (* Multiplies n by 2; a silly function. *) fun timestwo(0) = 0 timestwo(n) = 2 + timestwo(n - 1); Run the function for large values of n. Q:Why is it so slow? A:Each call must wait for the results of all the other calls to return before it can add 2 and return its own result. 10

Tail recursion tail recursion: When the end result of a recursive function can be expressed entirely as one recursive call. Tail recursion is good. A smart functional language can detect and optimize it. If a call f(x)makes a recursive call f(y), as its last action, the interpreter can discard f(x) from the stack and just jump to f(y). Essentially a way to implement iteration recursively. 11

Times-two function revisited This code is not tail recursive because of 2 + (* Multiplies n by 2; a silly function. *) fun timestwo(0) = 0 timestwo(n) = 2 + timestwo(n - 1); Exercise: Make the code faster using an accumulator. accumulator: An extra parameter that stores a partial result in progress, to facilitate tail recursion. 12

Iterative times-two in Java // Multiplies n by 2; a silly function. public static int timestwo(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + 2; } return sum; } 13

Iterative times-two in Java, v2 // Multiplies n by 2; a silly function. public static int timestwo(int n) { int sum = 0; while (n > 0) { sum = sum + 2; n = n - 1; } return sum; } 14

Tail recursive times-two in ML (* Multiplies n by 2; a silly function. *) fun timestwo(n) = let help(sum, 0) = sum help(sum, k) = help(sum + 2, k - 1) in help(0, n) end; Accumulator variable sum grows as n(k) shrinks. 15

Efficiency and Fibonacci The fibonaccifunction we wrote previously is also inefficient, for a different reason. It makes an exponential number of recursive calls! Example: fibonacci(5) fibonacci(4) fibonacci(3)» fibonacci(2)» fibonacci(1) fibonacci(2) fibonacci(3) fibonacci(2) fibonacci(1) How can we fix it to make fewer (O(n)) calls? 16

Iterative Fibonacci in Java // Returns the nth Fibonacci number. // Precondition: n >= 1 public static int fibonacci(int n) { if (n == 1 n == 2) { return 1; } int curr = 1; // the 2 most recent Fibonacci numbers int prev = 1; } // k stores what fib number we are on now for (int k = 2; k < n; k++) { int next = curr + prev; // advance to next prev = curr; // Fibonacci number curr = next; } return curr; 17

Efficient Fibonacci in ML (* Returns the nth Fibonacci number. Precondition: n >= 1 *) fun fib(1) = 1 fib(2) = 1 fib(n) = let fun helper(k, prev, curr) = if k = n then curr else helper(k + 1, curr, prev + curr) in helper(2, 1, 1) end; 18

The print function (4.1) print(string); The type of print is fn : string -> unit unitis a type whose sole value is () (like voidin Java) unlike most ML functions, print has a side effect(output) printaccepts only a string as its argument can convert other types to string: Int.toString(int), Real.toString(real), Bool.toString(bool), str(char), etc. 19

"Statement" lists (expression; expression; expression) evaluates a sequence of expressions; a bit like {}in Java the above is itself an expression its result is the value of the last expression might seem similar to a let-expression... but a let modifies the ML environment (defines symbols); a "statement" list simply evaluates expressions, each of which might have side effects 20

Using print - fun printlist([]) = () = printlist(first::rest) = ( print(first ^ "\n); printlist(rest) ); val printlist= fn : string list -> unit - printlist(["a", "b", "c"]); a b c val it = () : unit 21

print for debugging (* Computes n!; not tail recursive. *) fun factorial(0) = 0 factorial(n) = ( print("n is " ^ str(n)); n * factorial(n - 1) ); Useful pattern for debugging: ( print(whatever); your original code ) 22