CSC151 2007S, Class 19: Tail Recursion Admin: * Exam due (electronic and hardcopy) * Extra credit (EC) for attending today's Mathematics and Statistics Student Seminar. Noon, in 3821 * The President's Office scheduled me for a meeting at 1pm today (and another at 2:30 pm) * No office hours this afternoon, and I will be unavailable all afternoon. * No, I am not getting fired. I chair the Science Division, and have endless administrative responsibilities. * Reading for tomorrow: Recursion, Revisited. * Slowing things down a bit. Overview: * The key idea of recursion. * The simple form of recursion. * An example from Friday's lab: Sum red components. * A new technique: Passing along intermediate results. * An example from the reading: Difference * Special case: Tail recursion. /Friday: The Topic was Recursion/ * A procedure calls itself. * Permits you to do stuff "a buncha times" * What's the form? * A base case. For lists, typically "Is the list null?" * Sometimes another test. For lists, typically performed on the car. * Also call the procedure on the cdr. (define _PROC_ (lambda (lst) (if (null? lst) _BASE COMPUTATION_ (_COMBINE_ (car lst) (_PROC_ (cdr lst)))))) a (define sum (lambda (lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst)))))) ; New Goal: Given a list of colors, sum the red components of those ; colors. (define red-sum (lambda (lst) (if (null? lst) 0 (+ (rgb.red (car lst)) (red-sum (cdr lst)))))) (define some-colors (list color.red color.green color.blood-red color.neon-avocado)) (define new-red-sum (lambda (lst) (sum (map rgb.red lst))))a Design idea for recursive procedures: Write a hepler that can carry along the partially-computed result (define sum-red (lambda (colors) (sum-red-helper 0 colors))) (define sum-red-helper (lambda (sum-so-far remaining-colors) (if (null? remaining-colors) sum-so-far (sum-red-helper (+ sum-so-far (rgb.red (car remaining-colors))) (cdr remaining-colors))))) When you use this technique AND do nothing with the recursive result (other than use it), your procedure is "tail recursive" THE FOLLOWING PARENS AND OPERATIONS ARE FROM TRADITIONAL MATH, NOT SCHEME 1 - 2 - 3 - 4 - 5 ((((1 - 2) - 3) - 4) - 5) vs. (1 - (2 - (3 - (4 - 5))))