foldr CS 5010 Program Design Paradigms Lesson 5.4

Similar documents
ormap, andmap, and filter

Rewriting your function using map and foldr

Solving Your Problem by Generalization

More About Recursive Data Types

From Templates to Folds

Halting Measures and Termination Arguments

Lists of Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 5.3

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

CS 5010 Program Design Paradigms Lesson 6.1

Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 4.1

Lists of Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 6.5

Larger K-maps. So far we have only discussed 2 and 3-variable K-maps. We can now create a 4-variable map in the

Trees. CS 5010 Program Design Paradigms Bootcamp Lesson 5.1

Trees. CS 5010 Program Design Paradigms Lesson 6.2

Case Study: Undefined Variables

9.8 Graphing Rational Functions

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

COMP 250 Fall graph traversal Nov. 15/16, 2017

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

Binary recursion. Unate functions. If a cover C(f) is unate in xj, x, then f is unate in xj. x

Composite functions. [Type the document subtitle] Composite functions, working them out.

Observer Templates. CS 5010 Program Design Paradigms Lesson 1.4

Using Inheritance to Share Implementations

Repetition Through Recursion

Binary Search. CS 5010 Program Design Paradigms Bootcamp Lesson 8.2

Neighbourhood Operations

Math 1314 Lesson 24 Maxima and Minima of Functions of Several Variables

The Design Recipe Fall 2017

Understanding Signal to Noise Ratio and Noise Spectral Density in high speed data converters

Concavity. Notice the location of the tangents to each type of curve.

Chapter 3 Image Enhancement in the Spatial Domain

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

CSE 341 Section Handout #6 Cheat Sheet

The λ-calculus. 1 Background on Computability. 2 Programming Paradigms and Functional Programming. 1.1 Alan Turing. 1.

Piecewise polynomial interpolation

Case Study: Free Variables

2. Getting Started with the Graphical User Interface

How to Design Programs

Expression Values Operators. (string-append a b c ) a, b, c string-append. (substring abcd 0 2) abcd, 0, 2 substring

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

Compiler construction

The Design Recipe Fall 2018

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

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.

CS 161: Design and Analysis of Algorithms

Module 8: Local and functional abstraction

ROBUST FACE DETECTION UNDER CHALLENGES OF ROTATION, POSE AND OCCLUSION

Decision Support Systems for E-Purchasing using Case-Based Reasoning and Rating Based Collaborative Filtering

The λ-calculus. 1 Background on Computability. 2 Some Intuition for the λ-calculus. 1.1 Alan Turing. 1.2 Alonzo Church

Some Inequalities Involving Fuzzy Complex Numbers

Contracts, Purpose Statements, Examples and Tests

Administrivia. Simple data types

9.3 Transform Graphs of Linear Functions Use this blank page to compile the most important things you want to remember for cycle 9.

Generell Topologi. Richard Williamson. May 6, 2013

A Proposed Approach for Solving Rough Bi-Level. Programming Problems by Genetic Algorithm

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

CS3: Introduction to Symbolic Programming. Lecture 14: Lists.

Basics of Inheritance

Doing it in Java. CS 5010 Program Design Paradigms Bootcamp Lesson 5.4

Design and Realization of user Behaviors Recommendation System Based on Association rules under Cloud Environment

Working with images and scenes

Computer Data Analysis and Plotting

2. Design Planning with the Quartus II Software

MAPI Computer Vision. Multiple View Geometry

Automated Planning for Feature Model Configuration based on Functional and Non-Functional Requirements

CS485/685 Computer Vision Spring 2012 Dr. George Bebis Programming Assignment 2 Due Date: 3/27/2012

Global Constraints. Combinatorial Problem Solving (CPS) Enric Rodríguez-Carbonell (based on materials by Javier Larrosa) February 22, 2019

Typed Scheme: Scheme with Static Types

Skill Sets Chapter 5 Functions

Model-View-Controller Architecture

6.001 Notes: Section 8.1

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

The purpose of this lesson is to familiarize you with the basics of Racket (a dialect of Scheme). You will learn about

Status. We ll do code generation first... Outline

THE FINANCIAL CALCULATOR

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

Working with recursion

Introduction to Scratch Programming v1.4 (Second Ed) Lesson 6 Calculator

Proceedings of the Sixth International Workshop on Graph Transformation and Visual Modeling Techniques (GT-VMT 2007)

The Data Design Recipe

CS115 - Module 9 - filter, map, and friends

Computer Data Analysis and Use of Excel

Automatic Video Segmentation for Czech TV Broadcast Transcription

Lazy evaluation. Lazy evaluation (3) Lazy evaluation (2) Lazy execution. Example. Declarative Concurrency. Lazy Execution (VRH 4.

1-2. Composition of Functions. OBJECTIVES Perform operations with functions. Find composite functions. Iterate functions using real numbers.

Laboratory: Recursion Basics

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Proceedings of HotOS IX: The 9th Workshop on Hot Topics in Operating Systems

A Classification System and Analysis for Aspect-Oriented Programs

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

MATRIX ALGORITHM OF SOLVING GRAPH CUTTING PROBLEM

First Video Streaming Experiments on a Time Driven Priority Network

Learning Implied Global Constraints

Scheduling in Multihop Wireless Networks without Back-pressure

Case by Case. Chapter 3

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

Querying Complex Spatio-Temporal Sequences in Human Motion Databases

Section II. Nios II Software Development

CS 314 Principles of Programming Languages

Transcription:

oldr CS 5010 Program Design Paradigms Lesson 5.4 Mitchell Wand, 2012-2014 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 1

Introduction In this lesson, we will explore another common pattern in unctions deined by the list template. We will generalize this to a unction called oldr. We will visualize how oldr works, and show an important application area. 2

Learning Objectives At the end o this lesson you should be able to: describe, recognize, and use the oldr pattern. 3

What else could be dierent? ;ListONumber -> ListONumber (deine (add-1-to-each lon) (cond [(empty? lon) empty] [(else (cons (add1 (irst lon)) (add1-to-each (rest lon))))])) ;ListOEmployee -> ListOString (deine (extract-names lop) (cond [(empty? lop) empty] [else (cons (Employee-name (irst lop)) (extract-names (rest lop)))])) Here is the example we used to introduce map. In this example, both o the brown unctions are cons, but in some other unction there could be something else in that position. 4

Another example ;; ListONumber -> Number (deine (sum lon) (cond [(empty? lon) 0] [else (+ (irst lon) (sum (rest lon)))])) ;; ListONumber -> Number (deine (product lon) (cond [(empty? lon) 1] [else (* (irst lon) (product (rest lon)))])) Both these unctions take a list o numbers and return a number. sum returns the sum o the elements o the given list. product returns the product o the elements o the given list. These unctions are just alike, except or the dierences marked in red and green. 5

Let's generalize these sum and product can be generalized to a unction we call oldr, with two new arguments: one called cn, or the unction in the green position, and one called val, or the value in the red position. The strategy or oldr is using the template or ListOX on its list argument. Our original sum and product unctions can be recreated by supplying + and 0, or * and 1, as the two arguments. The strategy or these new versions o sum and product is "Use HOF oldr on...". The name oldr is a standard name or this unction, so that is the name we will use. oldr is already deined in ISL, so you don't need to write out the deinition. Let's look at the code: 6

Create two new arguments or the two dierences. We call this "oldr" (we'll explain the name later) (deine (oldr cn val lon) (cond [(empty? lon) val] [else (cn (irst lon) (oldr cn val (rest lon)))])) ;; strategy: Use HOF oldr on lon (deine (sum lon) (oldr + 0 lon)) (deine (product lon) (oldr * 1 lon)) This is predeined in ISL, so you don't need to write out this deinition 7

What is the purpose statement? ;; oldr : (X Y -> Y) Y ListOX -> Y ;; RETURNS: the result o applying on the ;; elements o the given list ;; rom right to let, starting with base. ;; (oldr base (list x_1... x_n)) ;; = ( x_1... ( x_n base)) 8

What is the contract or oldr? Based on our two examples we might guess the ollowing contract or oldr: Here is one guess or the contract or oldr, based on our two examples: oldr : (Number Number -> Number) Number ListONumber -> Number This works, because + and * both have contract (Number Number -> Number), and 0 and 1 are both numbers. 9

What is the contract or oldr? But there is nothing in the deinition o oldr that mentions numbers, so oldr could work at contract (X X -> X) X ListOX -> X that is, you could use oldr at (Boolean Boolean) Boolean ListOBoolean -> Boolean or (Employee Employee) Employee ListOEmployee -> Employee 10

Let's watch oldr compute on this list cn y4 x4 x4 cn y3 x3 x3 cn y2 x2 x2 cn y1 x1 empty x1 val Step through the animation to watch the computation o (oldr cn val (list x4 x3 x2 x1)) 11

What can we learn rom this? The base value val is a possible 2 nd argument to cn. The result o cn becomes a 2 nd argument to cn. So this will work as long as val, the 2 nd argument to cn, and the result o cn are all o the same type. So cn must satisy the contract (X Y -> Y) or some X and Y. 12

What else can we learn? The elements o the list become the irst argument to cn. So i cn satisies the contract (X Y -> Y), then the list must be o type ListOX. So the contract or oldr is: oldr : (X Y -> Y) Y ListOX -> Y 13

The contract or oldr (again!) The contract or oldr is oldr : (X Y -> Y) Y ListOX -> Y So oldr takes 3 arguments: a combiner unction that satisies the contract (X Y -> Y) a base value o type Y and a list o X's. And it returns a value o type Y. 14

Another picture o oldr Here's another visualization o oldr that you may ind helpul. ( x1 x2 x3 x4 x5 ) val (oldr val (list x1... x5)) 15

What kind o data is on each arrow? x_i Y Y X Y 16

We can think o oldr as starting with the base value val, and putting it through a pipeline o 's, where each also takes one o the x's as an input. The x's are taken right-to-let, which is why it is called oldr. ( x1 x2 x3 x4 x5 ) val (oldr a (list x1... x5)) 17

Another example: ;; strategy: combine simpler unctions (deine (add1-i-true b n) (i b (+ n 1) n))) ;; strategy: Use HOF oldr on lob (deine (count-trues lob) (oldr add1-i-true 0 lob)) Or even better: ;; strategy: Use HOF oldr on lob (deine (count-trues lob) (local ((deine (add1-i-true b n) (i b (+ n 1) n))) (oldr add1-i-true 0 lob))) What is the contract or add1-i-true? At what contract is oldr being used in this example? What is returned by count-trues? Try to answer these questions beore proceeding to the next slide. 18

What are the contracts? add1-i-true : Boolean Number -> Number In general: oldr : (X Y -> Y) Y ListOX -> Y In this case, X = Boolean and Y = Number, so we are using oldr at the contract (Boolean Number -> Number) Number ListOBoolean -> Number and thereore count-trues : ListOBoolean -> Number 19

Local unctions need contracts and purpose statements too (deine (count-trues lob) (local (; add1-i-true : Boolean Number -> Number ; RETURNS: the number plus 1 i the boolean is ; true, otherwise returns the number unchanged. (deine (add1-i-true b n) (i b (+ n 1) n))) (oldr add1-i-true 0 lob))) They count as help unctions, so they don't need separate tests. Local unctions need their deliverables, too. They count as help unctions, so they don't need separate tests. I they are complicated enough to need examples or tests, then you should make them independent unctions with a ull set o deliverables. 20

The whole thing (less examples and tests) ;; count-trues : ListOBoolean -> Number ;; RETURNS: the number o trues in the given list o booleans. ;; STRATEGY: Use HOF oldr on lob (deine (count-trues lob) (local (; add1-i-true : Boolean Number -> Number ; RETURNS: the number plus 1 i the boolean is ; true, otherwise returns the number unchanged. (deine (add1-i-true b n) (i b (+ n 1) n))) (oldr add1-i-true 0 lob))) 21

Mapreduce (mapreduce v g lst) = (oldr v (map g lst)) Thereore: (mapreduce v g (list x1... xn)) = ( (g x1) ( (g x2) ( (g x3)... v))) You may have heard o mapreduce, which is used or processing large data sets. We can deine mapreduce using our unctions as shown here. 22

Why mapreduce wins One o the great things about mapreduce is that it can oten be computed in parallel. I is associative, and v is its identity, can turn the calls to into a tree and do them in parallel on a server arm! For a data set o size n, this reduces the processing time rom n to log(n). Here is a picture: 23

From linear time to logarithmic ( (g x1) ( (g x2) ( (g x3) ( (g x4) v)))) = g g g g x1 x2 x3 x4 24

Where does the data come rom? The data might not be a list. It might be data extracted rom a large database. So your application would have 2 parts some SQL to extract a table ull o data (like "map") the unction you want to reduce the data with. The SQL insulates your application rom the physical layout o the DB; the SQL query optimizer can probably get your data out o the DB ast. mapreduce systems (like Hadoop) allow you to conigure the 'reduce' phase to make use o the available hardware. 25

Summary You should now be able to: describe, recognize, and use the oldr pattern. state the contracts or ormap, andmap, and ilter and oldr, and use them appropriately. combine these unctions using higher-order unction combination. 26

Next Steps I you have questions about this lesson, ask them on the Discussion Board Do Guided Practice 5.4 Go on to the next lesson 27