26
Foldr and Foldl CS 5010 Program Design Paradigms “Bootcamp” Lesson 7.5 1 © Mitchell Wand, 2012-2014 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Foldr andFoldl

CS5010ProgramDesignParadigms“Bootcamp”Lesson7.5

1©MitchellWand,2012-2014ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.

Page 2: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

LessonOutline

• Lookmorecloselyatfoldr• Introducefoldl:likefoldr but"intheotherdirection"

• Implementfoldl usingacontextvariable• Lookatanapplication

2

Page 3: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

LearningObjectives

• Attheendofthislessonyoushouldbeableto:– explainwhatfoldr andfoldl compute– explainthedifferencebetweenfoldr andfoldl– explainwhytheyarecalled"foldright"and"foldleft"

– usefoldl inafunctiondefinition

3

Page 4: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Foldr:thegeneralpicture

4

( )x1

f

x3

f

x2

f

x4

f

x5

f a

(foldr f a (list x1 ... x5))

Page 5: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

AnotherpictureoffoldrThetextbooksays:

;; foldr : (X Y -> Y) Y ListOfX -> Y ;; (foldr f base (list x_1 ... x_n)) ;; = (f x_1 ... (f x_n base))

Thismaybeclearerifwewritethecombinerininfix:eg (x- y)insteadof(fxy):

(foldr – a (list x1 ... xn)) =x1 – (x2 – (... – (xn – a)))

5

Weuse– insteadof+,because– isnotassociative.Soitmakesadifferencewhichwayyouassociatex1– x2– x3– x4

Page 6: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Whatifwewantedtoassociatetheotherway?

Insteadofx1 – (x2 – (... – (xn – a)))suppose we wanted(((a – x1) – x2) ... – xn)

6

foldr associatesitsoperatortotheright

foldlwillassociateitsoperatortotheleft

Page 7: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Forthiscomputation,thepipelinegoestheotherway

7

(foldl f a (list x1 ... x5))

( )x1

f

x3

f

x2

f

x4

f

x5

fa

Page 8: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Let'swritethecode

;; We'll use the template:(define (foldl f a lst)(cond[(empty? lst) ...][else (...

(first lst) (foldl ... (rest lst)))])

8

We'llneedtofigureoutwhatgoeshere.

Page 9: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Whatiflst isempty?

• Whenthelistisempty,therearenostagesinthepipeline,so

(foldl f a empty) = a

9

( )x1

f

x3

f

x2

f

x4

f

x5

fa

Page 10: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Whatifthelistisnon-empty?

10

( )x1

f

x3

f

x2

f

x4

f

x5

fa

( )x3

f

x2

f

x4

f

x5

f(f x1 a)

=

Page 11: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Soforanon-emptylist

(foldl f a (cons x1 lst))= (foldl f (f x1 a) lst)

11

Page 12: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Puttingthistogether

(define (foldl f a lst)(cond[(empty? lst) a][else (foldl f

(f (first lst) a)(rest lst))]))

12

Page 13: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Let'sdoacomputation

(foldl - 1 (list 20 10 2))= (foldl - 19 (list 10 2)) ;20-1 = 19= (foldl - -9 (list 2)) ;10-19 = -9= (foldl - 11 empty) ;2-(-9) = 11= 11

13

Page 14: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

What'sthecontract?

14

( )x1

f

x3

f

x2

f

x4

f

x5

fa

Thispartislikefoldr:WecanlabelalltheverticalarrowsasX'sandallthehorizontalarrowsasY's,sothecontractbecomes

(X Y -> Y) Y ListOfX -> Y

Page 15: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

PurposeStatement(1)

• Textbookdescription:;; foldl : (X Y -> Y) Y ListOfX -> Y ;; (foldl f base (list x_1 ... x_n)) ;; = (f x_n ... (f x_1 base))

15

Page 16: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Canwedescribethisusinganinvariant?

• Todothis,let'sthinkaboutwhereweareinthemiddleofacomputation

• Atthispoint,we'veprocessedx1andx2,andwearelookingatthesublist (x3 ... xn)

16

(((a – x1) – x2) x3 ... – xn)

Page 17: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

PurposeStatementusinginvariantGIVEN: a function f, a value a, and a sublist lstWHERE: lst is a sublist of some larger list lst0AND: a is the result of applying f to some starting

element a0 and the elements of lst0 that are above lstRETURNS: the result of applying f to the starting element a0

and all the elements of lst0.

17

Here'sanalternatepurpose statementthatdescribesthesituationinthemiddleof thepipeline.

Youdon'thavetousethispurposestatement;youcanusetheonefromthebook ifitiseasierforyou.

Page 18: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Let'sapplythistosubtraction;; diff : NonEmptyListOfNumber -> Number;; GIVEN: a nonempty list of numbers;; RETURNS: the result of subtracting the numbers, from;; left to right.;; EXAMPLE:;; (diff (list 10 5 3)) = 2

;; We'll use the data definition;; NELON = (cons Number ListOfNumber)

18

Thiswasguidedpractice7.1

Page 19: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Code,withsimplepurposestatement

(define (diff nelst)(diff-inner (first nelst) (rest nelst)))

;; diff-inner : Number ListOfNumber;; RETURNS: the result of subtracting each of the numbers in lon;; from num(define (diff-inner num lon)(cond

[(empty? lon) num][else (diff-inner

(- num (first lon)) ;; this is (f a (first lon));; different order of arguments;; than foldl

(rest lon))]))

19

Page 20: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Code,withfancierpurposestatement(define (diff nelst)(diff-inner (first nelst) (rest nelst)))

;; diff-inner : Number ListOfNumber;; GIVEN: a number sofar and a sublist lon of some list lon0;; WHERE: sofar is the result of subtracting all the numbers in;; lon0 that are above lon.;; RETURNS: the result of subtracting all the numbers in lon0.(define (diff-inner sofar lon)(cond

[(empty? lon) sofar][else (diff-inner

(- sofar (first lon)) ;; this is (f a (first lon));; different order of arguments;; than foldl

(rest lon))]))

20

Youcoulduseeitherpurposestatement.

sofar isagoodnameforthisargument

Page 21: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Orusingfoldl(define (diff nelst)

(foldl(lambda (x sofar) (- sofar x)) ;; foldl wants an X Y -> Y(first nelst) (rest nelst)))

21

sofar isagoodnameforthisargument,becauseitdescribeswherethevaluecomesfrom.

Page 22: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Anotherapplication:Simulation

;; simulating a process

;; Wishlist:;; next-state : Move State -> State

;; simulate : State ListOfMove -> State;; given a starting state and a list of;; moves, find the final state

22

Page 23: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

AnApplication:Simulation;; strategy: structural decomposition on moves(define (simulate st moves)(cond[(empty? moves) st][else

(simulate(next-state (first moves) st)(rest moves)))]))

23

Page 24: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Orusingfoldl

(define (simulate initial-state moves)(foldlnext-state initial-statemoves))

24

Icarefullychosetheorderoftheargumentstomakethiswork.Ifnext-statetookitsarguments inadifferentorder,you'dhavetodothesamekindofthingwedidforsubtractionabove.

Page 25: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

Summary

• Youshouldnowbeableto:– explainwhatfoldr andfoldl compute– explainthedifferencebetweenfoldr andfoldl– explainwhytheyarecalled"foldright"and"foldleft"

– usefoldl inafunctiondefinition

25

Page 26: Lesson 7.5 Foldr and Foldl - Northeastern University 7.5 Foldr and F… · • At the end of this lesson you should be able to: – explain what foldrand foldlcompute – explain

NextSteps

• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard

• Goontothenextlesson

26