cs61a-td
OH: WF 11-2pm
CS61A Notes 11 – Concurrent Vectors In The Sky (v1.1)
Just When You Were Getting Used To Lists…
Finally we are now introducing to you what most of you already know – arrays.
You’ve
already seen them countless times, so I won’t go into them in detail.
Roughly, an array is a
contiguous block of memory – and this is why you can have “instantaneous”, random access
into the array, instead of having to traverse down the many pointers of a list.
Recall the
vector operators:
(vector [element1] [element2] .
..) ==> works just like (list [element1] .
..)
(make-vector [num]) ==> creates a vector of num elements, all unbound
(make-vector [num] [init-value]) ==> creates a vector of num elements, all set to init-value
(vector-ref v i) ==> v[i]; gets the ith element of the vector v
(vector-set! v i val) ==> v[i] = val; sets the ith element of the vector v to val
(vector-length v) ==> returns the length of the vector v
Beyond using different operators, there are a few big differences between vectors and lists:
Vectors of length N
o
a contiguous block of memory cells
o
O(1) for accessing any item in the vector
o
O(N) for adding an item to the middle of
the vector, since you have to move the
rest of the vector down
o
O(N) for growing a vector; note that you
have to reallocate another, larger block
of memory!
o
add 1 to index to get to the next element
o
you may have “unbound” elements in the
vector; that is, length of vector is not the
same as length of your valid data
Lists of length N
o
many units of two cells linked together
by pointers
o
O(N) for accessing an item
o
O(1) for inserting an item anywhere in
the list, assuming we have a pointer to
the location
o
O(1) for growing a list; just add it at the
beginning or the end (if you have a
pointer to the end)
o
cdr down a list
o
length of list is exactly the number of
elements you’ve put into the list
Note the last bullet.
With lists, you allocate a new piece of memory (using cons) when you
need to add an element, but with vector, you allocate all the memory you need first, even if
you don’t have enough data to fill it up.
Also, just as you can have deep lists, where elements of a list may be a list as well, you can
also have “deep” vectors, often referred to as n-dimensional arrays, where n refers to how
“deep” the deep vector is.
For example, a table would be a 2-dimensional array – a vector
of vectors.
Note that, unlike in, say, C, your each vector in your 2D table does NOT have to
have the same size!
Instead, you can have variable-length rows inside the same table.
In
this sense, the vectors of Scheme are more like the arrays of Java than C.
QUESTIONS
1.
Write procedure (vector-copy! src src-start dst dst-start length).
After the call, length
elements in vector src starting from index src-start should be copied into vector dst
starting from index dst-start.
STk> a ==> #(1 2 3 4 5 6 7 8 9 10)