Summer 2009 Midterm (30 pts) Prasad
1. Ambiguity in Grammars (3 + 2 pts)
When is a grammar
considered ambiguous? Prove that the following grammar is ambiguous.
(Note that <EXPR> is a nonterminal, while
if, then,
else,
and x are terminals.)
<EXPR> ::= if <EXPR>
then <EXPR> |
if <EXPR>
then <EXPR>
else <EXPR> | x
2.
Expression Translation (4 + 5 pts)
This problem is based on background material for the Java
programming assignment. Consider the following template for a collection of Java
programs (called Test), where <expr> can
be replaced with an expression derived from the grammar shown below. Note
that <expr>, <term>, and
<factor> are nonterminals, while
i, a, +, *, (, and )
are terminals. {} stands for Kleene star. Note
also that operator precedence is implicit in the productions, and
+ has precedence over *.
class Test {
static double f(int i, double a){
return <expr>;
}
public static void main(String[] args){
System.out.println(f(33,2.2));
}
}
<expr>
-> <term>
{
* <term>
}
<term> -> <factor>
{
+ <factor>
}
<factor> ->
i |
a
|
( <expr> )
The formal argument i
is located in register 0 and argument a
is located in register 1. The relevant MSIL instructions
are: ldarg.0, ldarg.1, conv.r8, add,
and mul.
(i) Write the MSIL code generated for the following arithmetic
expression:
a * (i + i) + a
(ii) Write the MSIL code generated for the following arithmetic expression
(assuming that * is
right associative and
+ is left associative):
(i +
i + i * i * i)
3. OOPL Concepts (3 + 3 pts)
4. Recursive Definition in Scheme (4
pts)
Write a function suffixes, which takes a list of
symbols L, and produces a list of all suffixes of L. E.g.,
(suffixes '(a b c d))
> ((a b c d) (b c d) (c d) (d) ())
5. Recursive Definition in Scheme (5
+ 1 pts)
Write a function linearize, which takes a nested
list of symbols L, and produces a flat list of symbols (by "promoting"
all the symbols to the top-level while preserving their left-to-right order). E.g.,
(linearize '(a b (e f (g)) c d))
> (a b e f g c d)
Is the length of the list (linearize L) always greater
than or equal to the length of the list L? Justify your answer.