Map/filter notes and exercises

# How to Design Programs: An Introduction to Programming and Computing

• Notes
• davidvictor
• 3

This preview shows pages 1–2. Sign up to view the full content.

WPI CS1102 Map/Filter Summary CS 1102 : Notes and Exercises on Map/Filter Review of Map and Filter Map and filter are two built-in looping constructs in Scheme; both consume a function and a list, but each performs a different operation on the list. Filter , as its name suggests, creates a list of all elements on which the function returns true, while map calls the given function on every element of the list, returning a new list of the results. As a reminder, here are their definitions: ;; filter : (alpha -> boolean) list[alpha] -> list[alpha] ;; extracts elements of list that satisfy predicate (define (filter pred alst) (cond [(empty? alst) empty] [(cons? alst) (cond [(pred (first alst)) (cons (first alst) (filter pred (rest alst)))] [else (filter pred (rest alst))])])) ;; map : (alpha -> beta) list[alpha] -> list[beta] ;; returns list of results from applying function to each element ;; of the input list (define (map f alst) (cond [(empty? alst) empty] [(cons? alst) (cons (f (first alst)) (map f (rest alst)))])) Okay, but what's interesting about map and filter? Why are they any better/worse/different from loops in other languages? They accept functions as arguments, which is different from the loops you've written before. Remember: functions are just a way of giving names to computations. Map and filter simply take the computation to do in the loop as an argument. Using map and filter makes your code cleaner, because

This preview has intentionally blurred sections. Sign up to view the full version.

This is the end of the preview. Sign up to access the rest of the document.
• Fall '07
• Fisler
• List comprehension, loop, travel agency, Lists of cities, Cities of present-day nations and states

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern