Title: CS153: Midterm Solutions
1CS153 Midterm Solutions
2Problem 1
E id num (L) L ? L E
Original
E id num (L) L ? E L
Fixed
This is just to make it clearly evident how to
write a parser for it (and in fact the next
slides uses this grammar)
E id num (L) L id L num L (L) L
?
Expanding
3Problem 2
datatype token ID of string NUM of int
LPAREN RPAREN datatype exp Id of string
Num of int App of exp list exception BadMatch
fun parse tl case (parseE tl) of (e,)
gt e (_,_) gt raise BadMatch
4Problem 2
- parseE token list -gt exp token list
( parseE token list -gt exp token list
) fun parseE tl case tl of
gt raise BadMatch (RPAREN _) gt
raise BadMatch ((ID s)tl') gt ((Id
s), tl') ((NUM n)tl') gt ((Num n), tl')
(LPARENtl') gt case parseL tl' of
(el,)
gt raise BadMatch
(el,RPARENtl'') gt (App el, tl'')
(el,_)
gt raise BadMatch
5Problem 2
- parseL token list -gt exp list token list
fun parseL tl case tl of gt (,tl)
(RPAREN tl') gt ( , tl ) ((ID s)tl')
gt let val (el, tl'') parseL tl' in
((Id s)el, tl'') end
((NUM n)tl') gt let val (el, tl'') parseL
tl' in ((Num n)el, tl'') end
(LPARENtl') gt case parseL tl' of
(el,) gt raise BadMatch
(el,RPARENtl'') gt let val (el', tl''')
parseL tl'' in ((App el)el', tl''')
end (el,_)
gt raise BadMatch
6Problem 3
i 0 for (x y x ! 0 x x - z) i i
2x
7Problem 3
t0 i t1 x t2 z
add t0, 0, 0 i 0 la t1, y lw t1,
0(t1) t1y la t2, z lw t2, 0(t2)
t2z j TEST loop0 add t0,t0,t1 i ix
add t0,t0,t1 i ix sub t1, t1, t2
x x-z TEST bne t1,zero,loop0 x ! 0
la t2, x sw t1, 0(t2) xt1 la t2,
i sw t0, 0(t2) it0
8Problem 3
i 0 for (x y x ! 0 x x - z) i i
2x
Notice that if z does not divide y, the code will
loop forever. Otherwise, k is an integer.
Note that when we get to the kth time around the
loop, it terminates before running, so it only
goes to k-1
continued
9Problem 3
Closed Form derivation (continued)
Since, ky/z, zy/k
10Problem 3
Closed Form solution
la t0, y lw t0, 0(t0) t0y la t1, z lw
t1, 0(t1) t1z div t0, t1 puts
(y/z) in lo, and (y mod z) in hi mfhi t1
t1 y mod z STUCK bne t1, 0, STUCK
if t1 ! 0, loop forever mflo t1 t1
k (y/z) addi t1, t1, 1 t1 k1 mul
t0, t0, t1 t0 y(k1) la t1, i sw
t0, 0(t1) it0 la t1, x sw 0, 0(t1)
x0