Docsity

CMSC 330 Homework 4: Context-Free Grammars Solutions, Assignments of Programming Languages

Toggle sidebar
bg1
CMSC 330 Homework #4– context–free grammars– solutions Fall 2005
1. Because we need more nonterminals than the number of letters between S and Z, we just continue using
nonterminals A and B.
S→array Tof Y;
T→[U]|V
U→U,W|W
V→V[W]|[W]
W→X..X|Y..Y|Z..Z|A..A
X→true |false
Y→Ya|Yb|Yc|a|b|c
Z→’x’ |’y’ |’z’
A→+B|-B|B
B→B0|B1|B2|B3|B4|B5|B6|B7|B8|B9|0|1|2|3|4|5|6|7|8|9
2. a. S →aa Sbb |²
b. S →TW
T→Uc
U→aUcc |V
V→Vb|²
W→Wd|²
c. S →aSa|bSb|aa |bb
d. Rewrite the language as ambnanam, which
makes it easier to see how the grammar
can be written.
S→aSa|T
T→bTa|ba
e. Rewrite the language as an−mambman−m,
which makes it easier to see how the gram-
mar can be written.
S→aSa|T
T→aTb|²
f. S →(S)S |²
g. S →aT|bU|²
T→bS|aTT
U→aS|bUU
h. S →UT |TV
T→aTb|²
U→Ua|a
V→Vb|b
i. S →aSd|aTc|bUd|bVc|²
T→aTc|bVc|²
V→bVc|²
U→bUd|bVc|²
3. S →T|V
T→UU
U→aUb|ab
V→aVb|aWb
W→bWa|ba
To show the grammar is ambiguous show two leftmost derivations, or two rightmost derivations, or two
parse trees, for a string such as abab. Here are two leftmost derivations:
S =⇒T =⇒UU =⇒abU =⇒abab
S =⇒V =⇒aWb=⇒abab
You can construct the corresponding parse trees.
1

Partial preview of the text

Download CMSC 330 Homework 4: Context-Free Grammars Solutions and more Assignments Programming Languages in PDF only on Docsity!

CMSC 330 Homework #4– context–free grammars– solutions Fall 2005

  1. Because we need more nonterminals than the number of letters between S and Z, we just continue using nonterminals A and B. S → array T of Y;

T → [U] | V

U → U,W | W

V → V[W] | [W]

W → X..X | Y..Y | Z..Z | A..A

X → true | false

Y → Ya | Yb | Yc | a | b | c

Z → ’x’ | ’y’ | ’z’

A → +B | - B | B

B → B 0 | B 1 | B 2 | B 3 | B 4 | B 5 | B 6 | B 7 | B 8 | B 9 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

2. a. S → aaSbb | ≤

b. S → TW T → Uc

U → aUcc | V

V → Vb | ≤

W → Wd | ≤

c. S → aSa | bSb | aa | bb

d. Rewrite the language as ambnanam, which makes it easier to see how the grammar can be written.

S → aSa | T

T → bTa | ba

e. Rewrite the language as an−mambman−m, which makes it easier to see how the gram- mar can be written.

S → aSa | T

T → aTb | ≤

f. S → (S)S | ≤

g. S → aT | bU | ≤

T → bS | aTT

U → aS | bUU

h. S → UT | TV

T → aTb | ≤

U → Ua | a

V → Vb | b

i. S → aSd | aTc | bUd | bVc | ≤

T → aTc | bVc | ≤

V → bVc | ≤

U → bUd | bVc | ≤

3. S → T | V

T → UU

U → aUb | ab

V → aVb | aWb

W → bWa | ba

To show the grammar is ambiguous show two leftmost derivations, or two rightmost derivations, or two parse trees, for a string such as abab. Here are two leftmost derivations: S =⇒ T =⇒ UU =⇒ abU =⇒ abab S =⇒ V =⇒ aWb =⇒ abab You can construct the corresponding parse trees.