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?

The text has a lot more information on building custom iterators and the process by which you define an iterator for particular pairs of functions. See Chapter 22 of HtDP for this material.

Practice Exercises with Map and Filter

Imagine a travel agency that maintains two databases: one of information about cities and one about flights between cities.

  ;; A city is a (make-city symbol list[symbol])
  (define-struct city (name features))

  (make-city 'new-york (list 'music 'museums 'baseball 'strong-accents))

  ;; A flight is a (make-flight symbol symbol number list[number])
  (define-struct flight (from to number dates))

  (make-flight 'boston 'new-york 675 (list 10 13))
  ;; this example says that flight 675 from boston to new-york
  ;; operates on the 10th and 13th of each month

Assume you have lists of cities and flights. Using these lists, you can write several functions to help implement a travel agency. As you work through these exercises, ask yourself which ones can be written with map/filter, which ones cannot, and which ones require nested lambdas instead of externally-defined functions. If you can write these and know why you wrote them as you did, you're in good shape with map and filter.

You can make up a whole host of other functions to write for practice. Be creative!