CSC151 2007S, Class 29: Numeric Recursion Admin: * Final reminder: Ian Young speaks at 4:30 about vim. * We have a photographer in class today. * Tomorrow's reading is not yet available. Sorry. Expect it tonight. * No TA Today :-( * What's worst? * Heck week: Week before fall or spring break * Hell week: Week 14 * Purgatory week: Week 13 * Finals week - No classes, makes it easier * Answer one: "All of 'em" * Answer two: "It depends on your schedule" * Are there questions on assignment 11? * Testing permutations doesn't work * Homework 11 is extra credit. * THe story of the sum 1 + 2 + 3 + ... + N Overview: * Recursion, Generalized. * Thinking About Natural Numbers. * Numeric Recursion. Suppose we wanted to compute Gauss's sum, and we didn't know the formula. What would we do? * Define a procedure (define sum-to-n (lambda (n) ....) Probably8 needs to be recursive, since we can't deal with "arbitrary" long inputs without some simplification (define sum-to-n (lambda (n) (if (TEST_FOR_BASE_CASE) (BASE_COMPUTATION) (COMBINE n (sum-to-n (SIMPLIFY n)))))) A BAD BAD BAD SOLUTION (define sum-to-n (lambda (n) (if (null? n) 0 or null or something (COMBINE n (sum-to-n (cdr n)))))) For numbers, natural base cases include "is n 1" or "is n 0" For numbers, natural ways to simplify include "subtract 1" and "divide by 2" (define sum-to-n (lambda (n) (if (= n 0) 0 (+ n (sum-to-n (- n 1)))))) (define sum-to-n (lambda (n) (if (= n 1) 1 (+ n (sum-to-n (- n 1)))))) (define sum-to-n (lambda (n) (if (= n 2) 3 (+ n (sum-to-n (- n 1)))))) ; What is (sum-to-n -1) ; "Success" ; We should check a precondition What is (sum-to-n 5) using the following definition of sum-to-n? (define sum-to-n (lambda (n) (if (= n 1) 1 (+ n (sum-to-n (- n 1)))))) (sum-to-n 5) => (+ 5 (sum-to-n (- 5 1))) => (+ 5 (sum-to-n 4)) => (+ 5 (+ 4 (sum-to-n (- 4 1)))) => (+ 5 (+ 4 (sum-to-n 3))) => (+ 5 (+ 4 (+ 3 (sum-to-n (- 3 1))))) => (+ 5 (+ 4 (+ 3 (sum-to-n 2)))) => (+ 5 (+ 4 (+ 3 (+ 2 (sum-to-n (- 2 1)))))) => (+ 5 (+ 4 (+ 3 (+ 2 (sum-to-n 1)))))