a. Leftmost Derivation for the Sentence S
To create a leftmost derivation for the sentence (1 then # 2 else 3) $ 4, we need to apply the grammar rules starting from the start symbol expr and at each step expand the leftmost non-terminal symbol until we have derived the sentence. So, the derivation steps would look as follows:
expr (Start with only non-terminal symbol which is expr)
expr $ expr (Apply expr : expr '$' expr)
( expr ) $ expr (Apply expr : '(' expr ')')
( expr then expr else expr ) $ expr (Apply expr : expr 'then' expr 'else' expr to the leftmost expr inside the parentheses)
( INT then expr else expr ) $ expr (Replace the leftmost expr with INT since 1 is an integer)
( 1 then expr else expr ) $ expr (Replace INT with 1)
( 1 then # expr else expr ) $ expr (Apply expr : '#' expr to the leftmost expr after then)
( 1 then # INT else expr ) $ expr (Replace the leftmost expr with INT for # 2)
( 1 then # 2 else expr ) $ expr (Replace INT with 2)
( 1 then # 2 else INT ) $ expr (Replace the leftmost expr remaining inside the parentheses with INT)
( 1 then # 2 else 3 ) $ expr (Replace INT with 3)
( 1 then # 2 else 3 ) $ INT (Replace the rightmost expr with INT since 4 is an integer)
( 1 then # 2 else 3 ) $ 4 (Replace INT with 4 to obtain the sentence S)
This derivation sequence shows how we can derive the given sentence using the grammar provided.
b. Proof of Ambiguity
To prove that the grammar given above is ambiguous, we must provide two different parse trees (or derivations) that generate the same sentence. Ambiguity arises when there is more than one leftmost derivation or more than one rightmost derivation for the same sentence.
Consider the following sentence for instance:
# INT $ # INT
We will try to derive this sentence in two ways:
Start with `expr`
-> `expr $ expr` (Using `expr : expr '$' expr`)
-> `# expr $ expr` (Using `expr : '#' expr` on the left `expr`)
-> `# INT $ expr` (Using `expr : INT` on the left `expr`)
-> `# INT $ # expr` (Using `expr : '#' expr` on the right `expr`)
-> `# INT $ # INT` (Using `expr : INT` on the right `expr`)
Start with `expr`
-> `# expr $ expr` (Using `expr : '#' expr` immediately)
-> `# INT $ expr` (Using `expr : INT` on the encoded `expr`)
-> `# expr $ # INT` (Swapping the order of applying rules)
-> `# INT $ # INT` (Using `expr : INT` on the left `expr`)
Since we can derive the sentence # INT $ # INT following two different sequences of rule applications, the grammar is ambiguous. The same sentence can be formed using different paths, which results in different parse trees. As such, a parser would not be able to unambiguously decide which tree to construct, implying the grammar does not clearly specify how to parse expressions of this language.