Sei sulla pagina 1di 5

Name: Nguyễn Đức Phi Hồng

ID : ITITIU17022
Principles of Programming Languages Exercises 4

Associativity
1. Assume that ADDOP is left-associative binary operator, which grammar is
unambiguous and ensures the associativity of ADDOP?
a. exp exp ADDOP term | term

term LP exp RP | INT

b. exp term ADDOP term | term

term LP exp RP | INT

c. exp exp ADDOP exp | term

term LP exp RP | INT

d. exp term ADDOP exp | term

term LP exp RP | INT

Answer: b and c
2. Assume that RELOP is none-associative binary operator, which grammar is
unambiguous and ensures the associativity of RELOP?

a. exp term RELOP term | term

term LP exp RP | INT

b. exp exp RELOP exp | term

term LP exp RP | INT

c. exp term RELOP exp | term

term LP exp RP | INT

d. exp exp RELOP term | term

term LP exp RP | INT


Answer: a and b
3.Assume that NOTOP is a prefix unary operator, which grammar is valid for
an expression using NOTOP?

a. exp term NOTOP exp | term

term BOOLLIT | LP exp RP

b. exp NOTOP term | term

term BOOLLIT | LP exp RP

c. exp exp NOTOP term | term

term BOOLLIT | LP exp RP

d. exp term NOTOP | term


term BOOLLIT | LP exp RP
Answer: a and b

Ambigous Grammars
1. Choose the ambigous grammars
a.A -> AcA | b
b. S -> aS | bS | a | b
c. S -> SS | a | b
d. A -> AcB | B
e. B -> yBz | t | xB
Answer: c
2. Which is NOT the unambiguous grammar of a list (no separator) of
declarations where decl is a non-terminal symbol representing a
declaration?
a. decls decl+

b. decls decl decls | decl

c. decls decl declp

declp decl declp |

d. decls decl decls | decl |


Answer: a

3.Which is NOT the unambiguous grammar of a CM-separated list of ID?

a. idl ID (CM ID)*


b. idl ID idlist

idlist CM ID idlist |

c. idl ID CM idl | ID |

d. idl ID CM idl | ID
Answer: a
Practice
1. Consider the CFG:
S -> ( L ) | a
L -> L , S | S
Draw parse trees for:
a/ (a, a)
S

L S

S a

a
b/ (a, ((a, a), (a, a)))
S

L S

S L

a L S

S L

L L S

L S S a

S a a

2.Write a CFG grammar for the language of well-formed parenthesized expressions

(), (()), ()(), (()()), etc.: OK


()), )(, ((()), (((, etc.: not OK
Answer:
S  SS | (S) | () |
3. Is the following grammar ambiguous?
A  A “and” A | “not” A | “0” | “1”
Because a string can have more than one parse tree so the following grammar is ambiguous

4.Develop grammars for the following cases

n m
a. L = {a b : n = m}
n m
b. L = {a b : n = 2m}
n m
c. L = {a b : n  m}
n m
d. L = {a b : n > m}
n m
e. L = {a b : n  m}

a/S → aSb | ɛ
b/S → abbS | ɛ
c/S → aSb | Sa | ɛ
d/S → aSb | Sa | a
e/S → S1 | S2
S1 → aS1b | S1b | b
S2 → aS2b | aS2 | a

Potrebbero piacerti anche