Exercise #4

In section 1.3.1 of the textbook, the authors develop a procedure sum that finds the sum of certain terms of a sequence of numbers. It is a higher-order procedure, in the sense that it takes other procedures as arguments: Specifically, in order to call the sum procedure, the programmer must supply another procedure that sum uses to compute each addend from its index (that is, its position in the sequence).

Sometimes, instead of just finding one such sum, we want to construct a whole sequence of cumulative totals of terms of a given sequence. For example, given the sequence of square numbers,

0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ...,

we'd like to construct this sequence of cumulative totals:

0, 1, 5, 14, 30, 55, 91, 140, 204, 285, 385, ... .

The term at position k in the cumulative sequence is the sum of all of the terms up to position k in the original sequence.

Write and test a higher-order procedure cumulative that takes two arguments, of which the first should be a unary procedure term and the second an exact integer starting-index, and returns a unary procedure. Term should map each index of a sequence into the corresponding term; for instance, to describe the first sequence shown above, we'd use the square procedure as the value of term. Starting-index should be the index of the initial term of the sequence; in the example above, starting-index will be 0. The procedure that cumulative constructs and returns should interpret its argument as an index and return the sum of all of the terms of the original sequence up to that index. So, for instance, the value of the procedure call

((cumulative square 0) 9)

should be 285 -- the sum of the terms of the sequence of squares, up to and including 92.

This exercise will be due at 9 a.m. on Wednesday, February 18.


This document is available on the World Wide Web as

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

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

created February 13, 2004
last revised February 13, 2004

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