8.6.0.14

Lecture 25: Accumulators

This assignment is due on Sunday, November 13 at 11:59pm. Submit it using Handin as assignment lecture25.

Exercise 1. Finish designing the following function. Do not use the built-in function reverse.
; rev : [ListOf X] -> [ListOf X]
; reverses the order of elements in the given list
(check-expect (rev empty) empty)
(check-expect (rev (list "man" "bites" "dog")) (list "dog" "bites" "man"))
(check-expect (rev (list       "bites" "dog")) (list "dog" "bites"))
(check-expect (rev (list               "dog")) (list "dog"))
Hint: fill in the list-processing template using the wishlist method.

Exercise 2. What’s the cumulative distance to Andrew station? Define it as a constant named ashmont-andrew.

The code written in the video above is available for your reference. To download it, don’t use “Save Page As” or “Save As”; use “Save Link As” or “Download Linked File” in your Web browser. If you can’t find the command, try right-clicking or two-finger-tapping or long-pressing.

Exercise 3. Finish designing this function using the accumulator:
; sum : [ListOf Number] -> Number
; returns the sum of the given numbers
(define (sum lon) (sum/a lon 0))
(check-expect (sum empty) 0)
(check-expect (sum (list 10 20 50)) 80)
 
; sum/a : [ListOf Number] Number -> Number
; returns the sum of the given numbers
; *Accumulator*: total is the sum of numbers seen so far
(define (sum/a lon total) ...)
Hint: Write sequences of examples and follow the template for processing a list. But if your recursive call looks like (sum/a (rest lon) total), then it is incorrect because it does not update the accumulator according to the accumulator statement.

Optional: Read Chapters 31–32 and 34 of the textbook.