This preview shows pages 1–3. Sign up to view the full content.
CS 61A
Midterm 3 solutions
Fall 2009
1. Box and pointer/what will Scheme print?
(a)
> (let ((ls '(1 2 3 4)))
(foreach (lambda (x) (set! x (+ x 1))) ls)
ls)
Result: (1 2 3 4)
This was a question about understanding the difference between SET!
and SETCAR!.
The SET! inside the FOREACH changes a local variable
of the lambda, but does nothing to the pairs in LS.
Scoring: 1 point, all or nothing.
(b)
> (define x '(a b))
> (define y '(c))
> (setcdr! y x)
> (setcar! (cdr x) '(d))
> y
Result: (c a (d))
Y > XX+
 .


.

V
/
V
c
X > XX>X/

:\

: \
V
V
V
a
b
X/


V
d
This was a straightforward list mutation.
The SETCDR! changes Y from
a oneelement list to one that also includes the elements of X, as if
we'd said (append! y x).
It's important that the pointer from the cdr
of Y points to /the pair/ that X points to, neither to the variable X
nor to the word A.
The SETCAR! changes the second element of X from
B to (D)  the list containing D.
That list is a pair, which must be
in the diagram; you can't just put "(D)" in the diagram!
Scoring: One point for the printed result, one for the diagram.
2.
Concurrency.
> (define y 4)
> (parallelexecute
(lambda () (set! y (* 3 y)))
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document(lambda () (set! y (+ y ( y 2)))) )
(a) Correct values of Y.
"Correct" with respect to concurrency means "a value that could have resulted
from a nonconcurrent (sequential) processing of the threads."
With two
threads, there are only two sequential orderings  first one first, or
second one first.
(In general, N threads can be sequentially ordered in
N! (N factorial) ways, so that's how many correct answers there are unless
multiple orders happen to have the same result.)
If we do the first one first, (set! y (* 3 y)) sets Y to (* 3 4) = 12.
Then (set! y (+ y ( y 2))) sets Y to (+ 12 ( 12 2)) = 22.
If we do the second one first, (set! y (+ y ( y 2))) sets Y to
(+ 4 ( 4 2)) = 6.
Then (set! y (* y 3)) sets it to (* 6 3) = 18.
So the two correct answers are 22 and 18.
(b) Additional incorrect values.
There are three of them.
The most obvious ones are the cases in which
both processes read the original Y=4, both do their calculations, and
whichever one stores its result second wins.
If the first thread wins, the answer is (* 3 4) = 12.
If the second thread wins, the answer is (+ 4 ( 4 2)) = 6.
The third case is the one in which thread 1 stores its result in between the
two times that thread 2 loads the value of Y.
Some people asked about whether
to assume lefttoright or righttoleft evaluation, but in fact the order
doesn't affect the result for this expression, because (+ 4 ( 12 2)) and
(+ 12 ( 4 2)) are both 14.
So the three possible incorrect answers are 12, 6, and 14.
Scoring:
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 Harvey

Click to edit the document details