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

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

Topic 5: Examples and higher-order functions

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

CSc 520. Principles of Programming Languages 11: Haskell Basics

Programming Languages and Compilers (CS 421)

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

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

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

CSc 520. Principles of Programming Languages 7: Scheme List Processing

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

CSc 520 Principles of Programming Languages. Examining Lists. Constructing Lists... 7: Scheme List Processing

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

CSc 372. Comparative Programming Languages. 13 : Haskell Lazy Evaluation. Department of Computer Science University of Arizona

Forward Recursion. Programming Languages and Compilers (CS 421) Mapping Recursion. Forward Recursion: Examples. Folding Recursion.

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

CSE399: Advanced Programming. Handout 2

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018

List Functions, and Higher-Order Functions

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSc 372. Comparative Programming Languages. 3 : Haskell Introduction. Department of Computer Science University of Arizona

Functions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CSc 520 Principles of Programming Languages

Lecture 10 September 11, 2017

Week 5 Tutorial Structural Induction

Recursion & Iteration

CSc 372. Comparative Programming Languages. 15 : Haskell List Comprehension. Department of Computer Science University of Arizona

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

CS 321 Programming Languages

Introduction to Prolog Paper Refs. Prolog tutor. Julian Verdurmen. Seminar Softw. tech. for teaching and learning. September 30, 2009

Accumulators! More on Arithmetic! and! Recursion!

CSCE 314 Programming Languages

Shell CSCE 314 TAMU. Higher Order Functions

How to Design Programs

A brief tour of history

Shell CSCE 314 TAMU. Functions continued

CSc 520 Principles of Programming Languages

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Continuations and Continuation-Passing Style

Continuation Passing Style. Continuation Passing Style

An introduction introduction to functional functional programming programming using usin Haskell

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

Introduction. CSc 372. Comparative Programming Languages. 22 : Prolog Lists. Department of Computer Science University of Arizona.

Parsing Scheme (+ (* 2 3) 1) * 1

School of Computer Science

CSc 520. Iterators. CLU-style Iterators... CLU-style Iterators. Principles of Programming Languages. Christian Collberg April 16, 2003

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

Patterns The Essence of Functional Programming

Functional programming in μscheme

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values

Lecture 6: Sequential Sorting

Memory Management. Memory Management... Memory Management... Interface to Dynamic allocation

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

What is tail position?

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

CSc 372 Comparative Programming Languages

CNS 4450 Analysis of Programming Languages Homework Assignments Fall 2011

CSE 341 : Programming Languages Midterm, Spring 2015

CSci 4223 Principles of Programming Languages

Functional Programming. Pure Functional Programming

CSc 372 Comparative Programming Languages

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

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

Programming Languages and Compilers (CS 421)

Chapter 3 Linear Structures: Lists

CSE341 Spring 2017, Midterm Examination April 28, 2017

n What is its running time? 9/18/17 2 n poor_rev [1,2,3] = n (poor_rev [1] = n ((poor_rev [1] =

CSc 520 Principles of Programming Languages

IKI30820 Logic Programming Programming Style and Techniques Slide 09

Attributes of Variable. Lecture 13: Run-Time Storage Management. Lifetime. Value & Location

Then you were asked to paint another fence that is 2m high and 400m long for the price of $80. Should you accept it?

Chapter 3 Linear Structures: Lists

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

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

Programming Paradigms

foldr CS 5010 Program Design Paradigms Lesson 5.4

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Lists. Michael P. Fourman. February 2, 2010

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Programming Languages and Techniques (CIS120)

BBM 201 DATA STRUCTURES

Consider the following EBNF definition of a small language:

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

What is tail position?

Lecture 4: Higher Order Functions

CSc 520 Principles of Programming Languages

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CSE341 Spring 2016, Midterm Examination April 29, 2016

Transcription:

Slide 7 2 Accumulative Recursion We can sometimes get a more efficient solution by giving the function one extra argument, the accumulator, which is used to gather the final result. We will need to use an extra function. In the case of the dots function, the stack recursive definition is actually more efficient. dots n = dots n "" dots 0 acc = acc dots n acc = dots (n-1) (acc ++ ".") Copyright c 2003 C. Collberg Gofer III Christian Collberg February 3, 2003 CSc 520 Principles of Programming Languages University of Arizona Accumulative Recursion... Stack Recursion The dots n function returns a string consisting of n dots. dots n = dots n "" dots 0 acc = acc The dots are stacked until we reach the terminating arm of the recursion. O(n) items are stored on the stack. Slide 7 3 dots n acc = dots (n-1) (acc ++ ".") dots 3 dots 3 "" dots 2 ("" ++ ".") dots 2 (".") dots 1 ("." ++ ".") dots 1 ("..") dots 0 (".." ++ ".") dots 0 () Slide 7 1 dots 0 = "" dots n = "." ++ dots (n-1) dots 3 "." ++ dots 2 "." ++ ("." ++ dots 1) "." ++ ("." ++ ("." ++ dots 0)) "." ++ ("." ++ ("." ++ "")) "." ++ ("." ++ ".") "." ++ ".."

Slide 7 6 Stack Recursion Over Lists Stack recursive functions all look very much alike. All we need to do is to fill in the template below with the appropriate values and functions. do is the operation we want to apply to every element of the list. combine is the operation we want to use to combine the value computed from the head of the list, with the value produced from the tail. Template: f [ ] = final val f (x:xs) = combine (do x) (f xs) Slide 7 4 Stack vs. Accumulative Recursion dots 3 "." ++ dots (3-1) dots 2 ".." "." ++ dots (2-1) dots 1 "." "." ++ dots (1-1) dots 0 "" "" dots 3 dots 3 "" dots (3-1) ("" ++ ".") dots 2 "." dots (2-1) ("." ++ ".") dots 1 ".." dots (1-1) (".." ++ ".") dots 0 f [ ] = final val f (x:xs) = combine (do x) (f xs) Stack vs. Accumulative Recursion... Slide 7 7 sumlist :: [Int] -> Int sumlist [] = 0 sumlist (x:xs) = x + sumlist xs final val=0; do x = x; combine="+" double :: [Int] -> [Int] double [] = [] double (x:xs) = 2*x : double xs final val=[]; do x = 2*x; combine=":" Slide 7 5 Notice how with stack recursion we re building the result on the way back up through the layers of recursion. This means that for each recursive call many arguments have to be stacked, until they can be used on the way back up. With accumulative recursion we re instead building the result on the way down. Once we re at the bottom of the recursion (when the base case has been reached) the result is ready and only needs to be passed up through the layers of recursion.

Accumulative Recursion Over Lists main calls aux, the function that does the actual work. main passes along init val, the value used to initiate the accumulator. Slide 7 10 maxlist [] = error() Example maxlist: maxlist (x:xs) = maxlist xs x maxlist [] acc = acc maxlist (x:xs) acc = maxlist xs (max x a) Slide 7 8 do is the operation we want to apply to every element of the list. combine is the operation we want to use to combine the value computed from the head of the list with the accumulator. Template: init val=head xs; do x = x; combine="max" The reverse Function The reverse of an empty list is the empty list. The reverse of a list (x:xs) is the reverse of xs followed by x. Slide 7 11 reverse [1,2] reverse [2] ++ [1] (reverse [] ++ [2]) ++ [1] ([] ++ [2]) ++ [1] [2] ++ [1] [2,1] In Gofer: Slide 7 9 sumlist xs = sumlist xs 0 Example sumlist: sumlist [] acc = acc sumlist (x:xs) acc = sumlist xs (x + acc) reverse :: [Int] -> [Int] reverse [] = [] reverse (x:xs) = (reverse xs) ++ [x] init val=0; do x = x; combine="+"

Slide 7 14 We can devise a more efficient solution by using accumulative recursion. At each step we tack the first element of the remaining list on to the beginning of the accumulator. reverse [1,2] reverse [1,2] [] reverse [2] (1:[]) reverse [] (2:[1]) [2,1] reverse xs = rev xs [] In Gofer: rev [] acc = acc rev (x:xs) acc = rev xs (x:acc) Slide 7 12 reverse reverse [2,3,4] ++ [1] (reverse [3,4] ++ [2]) ++ [1] ((reverse [4] ++ [3]) ++ [2]) ++ [1] (((reverse [] ++ [4]) ++ [3]) ++ [2]) ++ [1] ((([] ++ [4]) ++ [3]) ++ [2]) ++ [1] (([4] ++ [3]) ++ [2]) ++ [1] ([4,3] ++ [2]) ++ [1] [4,3,2] ++ [1] reverse reverse rev [] Each list append A ++ B Slide 7 15 rev [2,3,4] 1:[] rev [3,4] 2:[1] rev [4] 3:[2,1] rev [] 4:[3,2,1] There are O(n) applications of reverse. Each application of rev invokes : which is an O(1) operation. Total time = O(n). Slide 7 13 reverse [2,3,4] ++ [1] reverse [3,4] ++ [2] reverse [4] ++ [3] reverse [] ++ [4] [4,3,2] [4,3] [4] takes O(length A) time. There are O(n) applications of reverse, where n is the length of the list. Each application invokes append on a list of length O(n). Total time = O(n 2 ). [] [ ]

Summary The Offside Rule When does one function definition end and the next one begin? Accumulative recursion uses an extra parameter in which we collect new information as we go deeper into the recursion. Slide 7 18 The computed value is returned unchanged back up through the layers of recursion. Stack recursion performs much of the work on the way back up through the layers of recursion. Slide 7 16 cube x = Accumulative recursion is often more efficient than stack recursion. Textual layout determines when definitions begin and end. Homework occurs x xs returns the number of times the item x occurs in the list xs. 1. Write a stack recursive definition of occurs. The Offside Rule... The first character after the "=" opens up a box which holds the right hand side of the equation: Slide 7 19 2. Write an accumulative recursive definition of occurs. 3. Try the two definitions with a large list as input. How many cells/reductions do they use? occurs :: Template: Int -> [Int] -> Int? occurs 1 [3,1,4,5,1,1,2,1] 3 Slide 7 17 Any character to the left of the line closes the box and starts a new definition: cube x =...