Exercise #5

In exercise #4, we used procedures to represent sequences and developed a higher-order procedure cumulate to perform a transformation on a given sequence of numbers. In order to access a particular element of a sequence, we called the procedure that represented the sequence, giving it a position number (an ``index'').

Now we have seen a different representation of finite sequences in Scheme: We can use a list -- a chain of pairs -- to hold a sequence. We access elements of such a list either by means of the pair selectors (car for the first element, cadr for the second, and so on) or by providing the list and an index to the list-ref procedure.

When the elements of a list are numbers, we'd still like to be able to transform the sequence into a similar sequence of the same length, with the elements of the transformed sequence being the successive cumulative totals of the elements of the original sequence. For example, given a sequence containing the numbers 3, 1, 4, 1, 5, and 9, in that order, the transformed sequence should contain the numbers 3, 4, 8, 9, 14, and 23.

Write and test a Scheme procedure called list-cumulate that takes one argument, a list, and constructs and returns the list of cumulative totals.

> (list-cumulate (list 3 1 4 1 5 9))
(3 4 8 9 14 23)

You may find that it is helpful to write other Scheme procedures to address subproblems of the list-cumulate problem. Go right ahead.

This exercise will be due at 9 a.m. on Tuesday, February 24.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~stone/courses/scheme/exercises/5.xhtml

Validated as XHTML 1.1 by the World Wide Web Consortium Cascading Style Sheet validated by the World Wide Web Consortium

created February 20, 2004
last revised February 20, 2004

John David Stone (stone@cs.grinnell.edu)