How to Design Programs: An Introduction to Computing and Programming
[Go to
first
,
previous
,
next
page;
contents
;
index
]
Section 43
Changing Structures, Vectors, and Objects
This section introduces several small projects on programming with mutable structures. The ordering of the
subsections roughly matches the outline of the book, proceeding from simple classes of data to complicated ones and
from structural recursion to generative recursion with backtracking and accumulators.
43.1
More Practice with Vectors
Programming with mutable vectors is hardly ever needed in the kinds of programs that we encountered. Still, because
it is far more prevalent in conventional languages, it is an important skill and deserves more practice than section
41.2
suggests. This section covers sorting with vectors, but its goal is to practice reasoning about intervals when processing
vectors.
We encountered the idea of sorting as early as section
12.2
, where we designed the
sort
function. It consumes a list
of numbers and produces a list of numbers with the same items in sorted (ascending or descending) order. An
analogous function for vectors consumes a vector and produces a new vector. But, using vector mutation, we can also
design a function that changes the vector so that it contains the same items as before, in a sorted order. Such a
function is called an
IN

PLACE
SORT
because it leaves all the items inside the existing vector.
An inplacesort function relies exclusively on effects on its input vector to accomplish its task:
;; inplacesort : (vectorof number)
>
void
;; effect: to modify V such that it contains the same items
;; as before but in ascending order
(define (inplacesort V) ...)
Examples must demonstrate the effect:
(local ((define v1 (vector 7 3 0 4 1)))
(begin
(inplacesort v1)
(equal? v1 (vector 0 1 3 4 7))))
Of course, given that
inplacesort
consumes a vector, the true problem is to design the auxiliary function that
works on specific segments of the vector.
The standard template for a vectorprocessing function uses an auxiliary function:
(define (inplacesort V)
file:///C/Documents%20and%20Settings/Linda%20Graue...How%20to%20Design%20Programs/curriculumZH53.html (1 of 28) [2/5/2008 5:00:14 PM]
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document