CS153: Midterm Solutions - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

CS153: Midterm Solutions

Description:

E ::= id | num | (L) L ::= id L | num L | (L) L | Problem 1 ... Problem 2. parse: token list - exp. fun parse tl = case (parseE tl) of (e,[]) = e ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 11
Provided by: fasHa4
Category:

less

Transcript and Presenter's Notes

Title: CS153: Midterm Solutions


1
CS153 Midterm Solutions
2
Problem 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
3
Problem 2
  • parse token list -gt exp

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
4
Problem 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
5
Problem 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
6
Problem 3
  • Problem

i 0 for (x y x ! 0 x x - z) i i
2x
7
Problem 3
  • Loopy solution

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
8
Problem 3
  • Closed Form derivation

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
9
Problem 3
Closed Form derivation (continued)
Since, ky/z, zy/k
10
Problem 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
Write a Comment
User Comments (0)
About PowerShow.com