Winter 2009 Midterm Prasad
1. Ambiguity in Grammars (3 + 3 pts)
When is a context-free grammar ambiguous?
Show that the following grammar
is ambiguous. Rewrite it to obtain an unambiguous grammar.
<S> ::= <S> <S> | b
2.
Expression Translation (4 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 operator precedence is implicit 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> -> <var>
|
( <expr> )
<var> ->
i |
a
The formal argument i
is located in register 0 and argument a
is located in register 1. The relevant Java bytecode instructions
are: iload_0,
dload_1, i2d, iadd, imul, dadd,
and dmul.
Write the Java bytecode generated for the following arithmetic expression
(assuming that * is
left associative and
+ is right associative):
(i
* i + i + a)
3. OOPL Concepts (3 + 3
pts)
What are the benefits of (i) inheritance and
(ii) polymorphism?
4. Recursive Definition in Scheme (6 pts)
Write a function replace that takes three arguments: an old symbol, a
new symbol and a nested
list of symbols L, and produces a new nested list of symbols by replacing all
occurrences of the old symbol by the new symbol (at all levels). E.g.,
(replace 'a 'b '(a b c))
> (b b c)
(replace 'old 'new '( (old old)
x ((y old x)) )
>( (new new) x ((y new x)))
(replace 'old 'new '( ) )
>( )
5. General (4 + 4 pts)
(a)
What are the benefits of reserving keywords over allowing use of all identifiers
as variables?
(b) What is a control abstraction? What are the benefits of supporting control
abstractions as opposed to providing analogs of general low-level primitives
such as branch/jump instructions, labels instructions, etc?