a. Leftmost derivation for the sentence S = (1 then # 2 else 3) $ 4
The leftmost derivation means we always expand the leftmost non-terminal first. We will denote each step of derivation with =>.
Given the grammar, our goal is to derive the given sentence S. We will start with the initial non-terminal expr.
- expr
- expr '′expr//Applying"expr′' expr" production rule to
expr
- '(' expr ')' '$' expr // Applying "'(' expr ')'" production rule to the first
expr
- '(' expr 'then' expr 'else' expr ')' '$' expr // Applying "expr 'then' expr 'else' expr" production rule to the
expr inside the parentheses
- '(' INT 'then' expr 'else' expr ')' '$' expr // Applying "INT" production rule to the
INT
- '(' INT 'then' '#' expr 'else' expr ')' '$' expr // Applying "'#' expr" production rule to the second
expr
- '(' INT 'then' '#' INT 'else' expr ')' '$' expr // Applying "INT" production rule to the
INT after '#'
- '(' INT 'then' '#' INT 'else' INT ')' '$' expr // Applying "INT" production rule to the third
expr
- '(' INT 'then' '#' INT 'else' INT ')' '$' INT // Applying "INT" production rule to the final
expr
- ( INT then # INT else INT ) $ INT // removing non-terminal
expr as we have reached the terminal symbols everywhere
Now, by substituting the actual INT values as given in the sentence S:
( 1 then # 2 else 3 ) $ 4
b. Showing that the grammar is ambiguous
A grammar is ambiguous if there are multiple leftmost derivations (or similarly, multiple parse trees) for a single sentence, meaning there is more than one way to derive the sentence using the grammar's production rules.
Let's consider the sentence "1 2 3". This sentence can have at least two different leftmost derivations based on the grammar:
First possible leftmost derivation:
- expr
- expr '$' expr (first expr is expanded)
- expr '′expr′' expr (first expr is expanded again)
- INT '′e' expr (replace first expr with INT)
Second possible leftmost derivation:
- expr
- expr '$' expr (first expr is expanded)
- INT '$' expr (replace first expr with INT)
- INT '′expr′' expr (second expr is expanded)
- INT '′I' expr (replace second expr with INT)
These two derivations create different parse trees, which means that the precedence of the $ operator is not clearly defined, leading to ambiguity in the order of operations. The sentence "1 2 3" could be interpreted as either "(1 2) 3" or "1 (2 3)", each yielding potentially different results depending on the semantics of $. Since the grammar allows for both interpretations, the grammar is ambiguous.