Map/filter notes and exercises

How to Design Programs: An Introduction to Programming and Computing

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

View Full Document Right Arrow Icon
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
Image of page 1

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

View Full Document Right Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    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.

    Student Picture

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

  • Left Quote Icon

    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.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    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.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern