1 / 9

TeachScheme, ReachJava

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.

cadams
Télécharger la présentation

TeachScheme, ReachJava

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. TeachScheme, ReachJava Adelphi University Friday morning June 26, 2009

  2. Recall add-up function (define (add-up nums) (cond [(empty? nums) 0] [(cons? nums) (+ (first nums) (add-up (rest nums)))]))

  3. 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

  4. 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 +

  5. Another approach Of course, add-up-accum is less convenient to use. Easy fix: (define (add-up nums) (add-up-accum nums 0))

  6. 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]))]))

  7. Generalize Both functions look pretty similar. They differ in the answer to the "empty?" case, and how to combine (first nums) with so-far

  8. 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

  9. Are we done yet? • Fill out end-of-day survey • Fill out end-of-workshop survey • Eat • Go home • Sleep • Teach

More Related