CSc 372. Comparative Programming Languages. 21 : Haskell Accumulative Recursion. Department of Computer Science University of Arizona



Similar documents
Functional Programming in C++11

Lecture 11: Tail Recursion; Continuations

C++ INTERVIEW QUESTIONS

Semester Review. CSC 301, Fall 2015

>

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 7: Functional Programming Languages

Module 2 Stacks and Queues: Abstract Data Types

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

The countdown problem

UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING. Answer THREE Questions.

Template 1: Test Helicopter

Copyright 2013 wolfssl Inc. All rights reserved. 2

Recursion and Recursive Backtracking

Training Manual. Pre-Employment Math. Version 1.1

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Chapter 5. Recursion. Data Structures and Algorithms in Java

Detecting Pattern-Match Failures in Haskell. Neil Mitchell and Colin Runciman York University

Common Data Structures

Python for Rookies. Example Examination Paper

QUICK SETUP GUIDE: USB-MIDI Cubase AI4 / Motif XS Editor / Windows

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Lecture 12 Doubly Linked Lists (with Recursion)

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Programming Fundamentals. Lesson 20 Sections

Special Directions for this Test

Practical Generic Programming with OCaml

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

PROBLEMS (Cap. 4 - Istruzioni macchina)

Sample Questions Csci 1112 A. Bellaachia

Datatype-generic data migrations

ALGEBRA. Find the nth term, justifying its form by referring to the context in which it was generated

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Using Visual C++ and Pelles C

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

RECOMMENDED JAVA SETTINGS

Solving Problems Recursively

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Gluing things together with Haskell. Neil Mitchell

CmpSci 187: Programming with Data Structures Spring 2015

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Using Parametric Equations in SolidWorks, Example 1

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins.

Testing and Tracing Lazy Functional Programs using QuickCheck and Hat

QUICK SETUP GUIDE: Firewire/mLAN Windows Cubase AI4 / Studio Manager / Motif XS Editor / Windows

Optimising Your EAMS through Business Processes. Wyhan Jooste

Understand the role that hypothesis testing plays in an improvement project. Know how to perform a two sample hypothesis test.

Instructions for the Epson Perfection 1670 Scanner

Algorithms and Data Structures

Binary search algorithm

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?

Outline. CSc 466/566. Computer Security. 8 : Cryptography Digital Signatures. Digital Signatures. Digital Signatures... Christian Collberg

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Poor Man's Type Classes

Stack Allocation. Run-Time Data Structures. Static Structures

Introduction to Parallel Programming and MapReduce

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

AP Computer Science A 2004 Free-Response Questions

Modifying Colors and Symbols in ArcMap

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

WRITING DATA TO A BINARY FILE

LINEAR INEQUALITIES. less than, < 2x + 5 x 3 less than or equal to, greater than, > 3x 2 x 6 greater than or equal to,

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Pseudo code Tutorial and Exercises Teacher s Version

Text Processing In Java: Characters and Strings

A-level COMPUTER SCIENCE

Solutions to Quick Check Questions. Defining Your Own Classes Part 1

MQL4 COURSE By Coders guru

Lecture Outline. Stack machines The MIPS assembly language. Code Generation (I)

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

customer rewards Use this guide to create customized customer rewards and redeem points earned by customers.

Lecture 12: Abstract data types

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

Class 16: Function Parameters and Polymorphism

Code Obfuscation. Mayur Kamat Nishant Kumar

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

A Table of the Most Common Standard Pipe Sizes. Nominal Bore 1/2 inch (DN 15 mm), Outside Diameter mm

Project 2: Bejeweled

both double. A. T and v max B. T remains the same and v max doubles. both remain the same. C. T and v max

6. Standard Algorithms

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

SizmekFeatures. HTML5JSSyncFeature

Comp 248 Introduction to Programming

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Enter Here --> Photography Business Quick Steps > Get it Here <

Anatomy of Programming Languages. William R. Cook

From Interpreter to Compiler and Virtual Machine

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

How To Monitor Performance On A Microsoft Powerbook (Powerbook) On A Network (Powerbus) On An Uniden (Powergen) With A Microsatellite) On The Microsonde (Powerstation) On Your Computer (Power

Introduction to Java and Eclipse

Recursion vs. Iteration Eliminating Recursion

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Termination Checking: Comparing Structural Recursion and Sized Types by Examples

Transcription:

1/18 CSc 372 Comparative Programming Languages 21 : Haskell Accumulative Recursion Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg

2/18 Stack Recursion The dots n function returns a string consisting of n dots. The dots are stacked until we reach the terminating arm of the recursion. O(n) items are stored on the stack. dots 0 = "" dots n = "." ++ dots (n-1) dots 3 "." ++ dots 2 "." ++ ("." ++ dots 1) "." ++ ("." ++ ("." ++ dots 0)) "." ++ ("." ++ ("." ++ "")) "." ++ ("." ++ ".") "." ++ ".." "..."

3/18 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 ++ ".")

4/18 Accumulative Recursion... dots n = dots n "" dots 0 acc = acc dots n acc = dots (n-1) (acc ++ ".") dots 3 dots 3 "" dots 2 ("" ++ ".") dots 2 (".") dots 1 ("." ++ ".") dots 1 ("..") dots 0 (".." ++ ".") dots 0 ("...") "..."

5/18 Stack vs. Accumulative Recursion dots 3 "." ++ dots (3 1) dots 2 "." ++ dots (2 1) "..." ".." dots 3 dots 3 "" "..." dots (3 1) ("" ++ ".") dots 2 "." "..." dots 1 "." ++ dots (1 1) dots 0 "" "" "." dots (2 1) ("." ++ ".") dots 1 ".." "..." dots (1 1) (".." ++ ".") dots 0 "..." "..." "..."

6/18 Stack vs. Accumulative Recursion... 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.

7/18 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)

8/18 Stack Recursion Over Lists... f [ ] = final val f (x:xs) = combine (do x) (f xs) 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=":"

9/18 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. 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: main xs = aux xs init val aux [] acc = acc aux (x:xs) acc = aux xs (combine do x acc)

10/18 Accumulative Recursion Over Lists... main xs = aux xs init val aux [] acc = acc aux (x:xs) acc = aux xs (combine do x acc) sumlist xs = sumlist xs 0 Example sumlist: sumlist [] acc = acc sumlist (x:xs) acc = sumlist xs (x + acc) init val=0; do x = x; combine="+"

11/18 Accumulative Recursion Over Lists... main xs = aux xs init val aux [] acc = acc aux (x:xs) acc = aux xs (combine do x acc) Example maxlist: maxlist [] = error("...") maxlist (x:xs) = maxlist xs x maxlist [] acc = acc maxlist (x:xs) acc = maxlist xs (max x a) init val=head xs; do x = x; combine="max"

12/18 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. Examples: reverse [1,2] reverse [2] ++ [1] (reverse [] ++ [2]) ++ [1] ([] ++ [2]) ++ [1] [2] ++ [1] [2,1] In Haskell: reverse :: [Int] -> [Int] reverse [] = [] reverse (x:xs) = (reverse xs) ++ [x]

13/18 The reverse Function... reverse [1,2,3,4] 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] [4,3,2,1]

14/18 The reverse Function... reverse [1,2,3,4] reverse [] ++ [4] [4] [4,3,2,1] reverse [2,3,4] ++ [1] reverse [3,4] ++ [2] reverse [4] ++ [3] [4,3,2] [4,3] Each list append A ++ B 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 ). [] [ ]

15/18 The reverse Function... 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. Examples: reverse [1,2] reverse [1,2] [] reverse [2] (1:[]) reverse [] (2:[1]) [2,1] In Haskell: reverse xs = rev xs [] rev [] acc = acc rev (x:xs) acc = rev xs (x:acc)

16/18 The reverse Function... reverse [1,2,3,4] rev [1,2,3,4] [] [1,2,3,4] rev [2,3,4] 1:[] rev [3,4] 2:[1] rev [4] 3:[2,1] rev [] 4:[3,2,1] [1,2,3,4] [1,2,3,4] [1,2,3,4] [1,2,3,4] There are O(n) applications of reverse. Each application of rev invokes : which is an O(1) operation. Total time = O(n). [4,3,2,1] [1,2,3,4]

17/18 Summary Accumulative recursion uses an extra parameter in which we collect new information as we go deeper into the recursion. 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. Accumulative recursion is often more efficient than stack recursion.

18/18 Exercise occurs x xs returns the number of times the item x occurs in the list xs. 1 Write a stack recursive definition of occurs. 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? Template: occurs :: Int -> [Int] -> Int Examples:? occurs 1 [3,1,4,5,1,1,2,1] 4