Held: Friday, 13 February 2004
Today we consider vectors, which serve as alternates to lists. Vectors
differ from lists in three primary ways: vectors have fixed size, vectors are
indexed, and vectors are naturally mutable.
- There will be time for questions on the exam.
- I will be unavailable this weekend.
- Problems with lists.
- A solution: Vectors.
- Side note: The
- Now that we've worked with lists for a while, we've identified
some things that make lists inappropriate for some situations.
- List are expensive to use; to find the length of a list
or to access an element late in the list, you need to cdr down the
- Lists are fixed; you can't easily change an element of a
- At the same time, there are some advantages to lists:
- Lists are dynamic; it is easy to grow and shrink a list.
- Lists are inherently recursive; the type is defined
- Lists are simple; you can build almost every list operation
through just a few basic operations (
- For applications in which you need some of the features that lists
fail to provide, Scheme provides the alternative of vectors.
- Vectors provide constant-time access to their elements.
- Vectors are naturally mutable. That is, one of the key operations
on vectors is
set an element of the vector.
- Scheme also provides procedures to mutate lists, but those are
used only in special cases and their careless use can lead to
very confusing results.
- In order to provide these benefits, Scheme restricts vectors to
be of a fixed size.
- As you solve different problems, you'll need to decide which features
are most important to you (the dynamic size of lists or the
mutability and constant-time access of vectors).
- Operations whose primary purpose is to change a value (rather than to
create a new value) are called side-effecting operations.
- We sometimes find that we need to do more than one thing when working
with side-effecting operations.
- For example, we might modify a vector and then recurse, as in
list->vector from the reading.
- Scheme provides the simple
begin construct for
do more than one thing in sequence.
- Here's the form
- Note that this form is only useful when you have operations, like
vector-set!, that have side effects.
- Otherwise, all you're doing is computing values and then forgetting