90 likes | 103 Views
This text explains how to write a recursive function in Scheme to add up a list of numbers. It also provides an alternative approach using accumulation and shows a similar implementation in Java.
E N D
TeachScheme, ReachJava Adelphi University Friday morning June 26, 2009
Recall add-up function (define (add-up nums) (cond [(empty? nums) 0] [(cons? nums) (+ (first nums) (add-up (rest nums)))]))
Trace add-up function (add-up (list 3 5 2 1)) (+ 3 (add-up (list 5 2 1))) (+ 3 (+ 5 (add-up (list 2 1)))) (+ 3 (+ 5 (+ 2 (add-up (list 1))))) (+ 3 (+ 5 (+ 2 (+ 1 (add-up empty))))) ; lots of pending +'s (+ 3 (+ 5 (+ 2 (+ 1 0)))) (+ 3 (+ 5 (+ 2 1)))) (+ 3 (+ 5 3)) (+ 3 8) 11
Another approach (define (add-up-accum nums so-far) (cond [(empty? nums) so-far] [(cons? nums) (add-up-accum (rest nums) (+ (first nums) so-far))])) (add-up-accum (list 3 5 2 1) 0) (add-up-accum (list 5 2 1) (+ 3 0)) (add-up-accum (list 5 2 1) 3) (add-up-accum (list 2 1) (+ 5 3)) (add-up-accum (list 2 1) 8) (add-up-accum (list 1) (+ 2 8)) (add-up-accum (list 1) 10) (add-up-accum empty (+ 1 10)) (add-up-accum empty 11) 11 ; never more than 1 pending +
Another approach Of course, add-up-accum is less convenient to use. Easy fix: (define (add-up nums) (add-up-accum nums 0))
Another example ; multiply-positives : list-of-numbers -> number (define (multiply-positives nums) (mp-accum nums 1)) (define (mp-accum nums so-far) (cond [(empty? nums) so-far] [(cons? nums) (mp-accum (rest nums) (cond [(> (first nums) 0) (* (first nums) so-far)] [else so-far]))]))
Generalize Both functions look pretty similar. They differ in the answer to the "empty?" case, and how to combine (first nums) with so-far
In Java… See projects June26 v1 through June26 v5 v1: addUp written by structural recursion v2: addUp written by accumulative recursion v3: addUp becomes static, in a separate class v4: addUp written using for-each loop v5: addUp written using while-loop
Are we done yet? • Fill out end-of-day survey • Fill out end-of-workshop survey • Eat • Go home • Sleep • Teach