Side effects

Exercise 1

Develop a Scheme procedure zero-out-negatives! that takes any vector of real numbers as its argument and destructively replaces each of the negative values in the vector with 0, leaving the non-negative ones unchanged. You should expect that this procedure will normally be invoked only for its side effect, so it makes no difference what value the procedure returns.

Exercise 2

Develop a Scheme procedure reverse-vector! that takes any vector as argument and reverses the order of its elements, in place.

> (define sample-1 (vector 'alpha 'beta 'gamma 'delta))
> (reverse-vector! sample-1)
> sample-1
#(delta gamma beta alpha)
> (define sample-2 (vector "A" "man," "a" "plan," "a" "canal--" "Panama!"))
> (reverse-vector! sample-2)
> sample-2
#("Panama!" "canal--" "a" "plan," "a" "man," "A")
> (define sample-3 (vector))
> (reverse-vector! sample-3)
> sample-3
#()

Exercise 3

The spectrum of a list of natural numbers is a vector indicating the number of occurrences of each natural number up to and including the largest one that occurs in the list. The tally of the number of occurrences of a natural number k is found at position k of the vector.

For example, in the list (0 3 0 1 0 1 0 0 3 0 1), the natural number 0 occurs six times, the natural number 1 occurs three times, and the natural number 3 occurs twice; so the spectrum of this list is the vector #(6 3 0 2). The 0 entry the spectrum indicates the the natural number 2 did not occur at all.

Develop a Scheme procedure spectrum that constructs and returns the spectrum of a given list of natural numbers.

> (spectrum (list 0 3 0 1 0 1 0 0 3 0 1))
#(6 3 0 2)
> (spectrum (list 3 1 4 1 5 9))
#(0 2 0 1 1 1 0 0 0 1)
> (spectrum (list 12 12 12 12 24 12))
#(0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 1)
> (spectrum null)
#()

This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~stone/courses/scheme/labs/side-effects.xhtml

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

created September 20, 2001
last revised September 20, 2001

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