Exercise #8

The exercise this time involves writing a few utilities for stream operations, followed by an mathematical application.

Part (a)

Define and test a procedure, stream-drop, that takes a stream str and a non-negative integer len as arguments, and returns a stream just like str except that it lacks the first len elements. If, however, str contains len or fewer elements, then the stream that stream-drop returns should be the-empty-stream.

Part (b)

Define and test a procedure, stream-take, that takes a stream str and a non-negative integer len as arguments, and returns a stream just like str except that it stops after the first len elements. If, however, str contains len or fewer elements, then the stream that stream-take returns should be exactly like str.

Part (c)

Define and test a procedure, stream-filler, that takes a stream str and any value filler as its arguments and returns an infinite stream that is just like str except that, if str is finite, the stream that stream-filler returns goes on after str stops, producing the value filler at every subsequent position.

Part (d)

Define and test a procedure, stream-cycle, that takes a stream str as argument and returns a stream with the same elements as str, but repeated over and over, forever. (For example, if str is the stream consisting of the integers 0 and 1, in that order, then (stream-cycle str) should be an infinite stream, beginning with 0, in which the integers 0 and 1 appear alternately.) If, however, str is the empty stream, then (stream-cycle str) should also be the empty stream.

Part (e)

The convolution of two infinite streams left and right of numbers is an infinite stream in which the element in position n is

(+ (* (stream-ref left 0) (stream-ref right n))
   (* (stream-ref left 1) (stream-ref right (- n 1)))
   (* (stream-ref left 2) (stream-ref right (- n 2)))
   ...
   (* (stream-ref left (- n 1)) (stream-ref right 1))
   (* (stream-ref left n) (stream-ref right 0)))

In other words, the element in position n of the convolution is the sum of all the possible products of elements from left and right whose position numbers add up to n.

For instance, if left is the stream 0, 2, 4, 6, ... of even numbers, and right is the stream 1, 3, 5, 7, ... of odd numbers, then the convolution of left and right is the stream

0 * 1,
(0 * 3) + (2 * 1),
(0 * 5) + (2 * 3) + (4 * 1),
(0 * 7) + (2 * 5) + (4 * 3) + (6 * 1),
...

-- that is, the stream 0, 2, 10, 28, ... .

Define and test a procedure convolve that computes and returns the convolution of any two infinite streams.

This exercise will be due at 9 a.m. on Wednesday, April 14.


This document is available on the World Wide Web as

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

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

created April 8, 2004
last revised April 9, 2004

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