CSC151 2007S, Class 24: Recursion Basics, Continued * Like most of you, I'm incredibly frustrated by Friday's events. If there are recommendations you have for things to do in class, please let me know. * Grinnellians need to learn how to hyphenate * "Hate Free Grinnell" is an imperative that tells people to hate this thing called "Free Grinnell" * "Hate-Free Grinnell" is what we hope it would be. Admin: * Are there questions on Assignment 6? * The reading for Tuesday is available: Recursion with Helper Procedures. (Wouldn't you know that the first time I have a reading available far in advance, I delay it.) * I will do my best to distribute the next exam on Wednesday. (I've written a draft, but I want time to iron out bugs.) (How's that for a mixed metaphor?) Overview: * Designing a recursive procedure. * More time for lab. ==Reminder: Repetition== * Do an action again and again and again * Lots of known techniques: map, foreach!, (cutandpaste), image-transform!, image-variant, and image-compute-pixels! * But each is specific to a particular data type or kind of result * What if you want to do something different? * Enter recursion: General technique for repetitoin ==On to Recursion== * Idea: To solve a big problem * Solve a smaller version of the same kind of problem * Build up from that small solution to a big solutino * Concrete example: Summing a list * (sum lst) * Suppose someone can tell us the sum of the cdr of the list * How do we compute the sum of the overall list? Add the first term (the car) to the sum of the cdr * However, if the list is empty, there is no cdr, so ... we need to specify what the sum of the empty list should be (define sum (lambda (lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst)))))) (sum (list 1 2 3 4)) => (+ (car (list 1 2 3 4)) (sum (cdr (list 1 2 3 4)))) => (+ 1 (sum (list 2 3 4))) => (+ 1 (+ 2 (sum (list 3 4)))) => (+ 1 (+ 2 (+ 3 (sum (list 4))))) => (+ 1 (+ 2 (+ 3 (+ 4 (sum (list)))))) => (+ 1 (+ 2 (+ 3 (+ 4 0)))) => (+ 1 (+ 2 (+ 3 4))) => (+ 1 (+ 2 7)) => (+ 1 9) => 10 ;;; The following is not actual Scheme in action, but it's close enough (define my-colors (list black white green dark-grey yellow blue)) ; Assume black, dark-green, and blue are dark, nothing else is (rgb-filter-out-dark (list black white green dark-grey yellow blue)) => (rgb-filter-out-dark (list white green dark-grey yellow blue)) => (cons white (rgb-filter-out-dark (list green dark-grey yellow blue))) => (cons white (cons green (rgb-filter-out-dark (list dark-grey yellow blue)))) => (cons white (cons green (rgb-filter-out-dark (list yellow blue)))) => (cons white (cons green (cons yellow (rgb-filter-out-dark (list blue))))) => (cons white (cons green (cons yellow (rgb-filter-out-dark (list))))) => (cons white (cons green (cons yellow null))) => (cons white (cons green (list yellow))) => (cons white (list green yellow)) => (list white green yellow)