CSC151.02 2003F, Class 41: Tail Recursion Admin * Warning! Friday the 13th falls on Thursday * Homework due. * Read "Association Lists" Overview * Tail recursion * Building tail-recursive procedures * Lab * Reflection As Computer Scientists look at patterns of recursion, they see one key difference (define PROC (lambda (PARAMS) (if (TEST) BASE-CASE (COMBINE SOMETHING (PROC (SIMPLIFY PARAMS)))))) (define PROC (lambda (PARAMS) (if (TEST) BASE-CASE (PROC (SIMPLIFY PARAMS))))) (define member? (lambda (val lst) (cond ((null? lst) #f) ((eqv? val (car lst)) #t) (else (member? val (cdr lst)))))) Scheme is much more efficient if you use the second form of recursion. (define sumr (lambda (lst) (if (null? lst) 0 (+ (car lst) (sumr (cdr lst)))))) (define suml (lambda (lst) (sum-helper lst 0))) (define sum-helper (lambda (lst partial-sum) (if (null? lst) partial-sum (sum-helper (cdr lst) (+ partial-sum (car lst)))))) (sumr (list 1 2 3 4)) => (+ 1 (sumr (list 2 3 4))) => (+ 1 (+ 2 (sumr (list 3 4)))) => (+ 1 (+ 2 (+ 3 (sumr (list 4))))) => (+ 1 (+ 2 (+ 3 (+ 4 (sumr (list)))))) Just as we have to spend space and effort remembering "what to do after the recursion finishes", so does Scheme. Good Scheme programmers therefore try to write the second form of recursion, which we call "tail recursion". * Metaphor of "the world worm" (Norse?) How can you turn regular recursive procedures into tail-recursive procedures? * Different strategies. * Typically, build a tail-recursive helper with another parameter, the partial result Try it! You'll like it! Hey Mikey.