{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Map/filter notes and exercises

How to Design Programs: An Introduction to Programming and Computing

Info iconThis 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
Background image of page 1

Info iconThis 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 ]}