Docsity

Discussion Material for CMSC330: Grammar and Parsing (10/1), Assignments of Programming Languages

Toggle sidebar
bg1
CMSC330: Discussion Material (10/1)
October 1, 2008
1) What langage does the following grammar generate:
Sโ†’aSbS |bS aS |๎˜
Answer: The set of all strings with an equal number of aโ€™s and bโ€™s.
2)
a) Give the grammar that generates the language of the regular expression: 0*1(0 |1)*
Answer:
Sโ†’A1B
Aโ†’0A|๎˜
Bโ†’0B|1B|๎˜
b) Give the leftmost and rightmost derivations of the following strings using the grammar from part a):
i) 1001
Answer:
Leftmost: Sโ†’A1Bโ†’1Bโ†’10Bโ†’100Bโ†’1001Bโ†’1001
Rightmost: Sโ†’A1Bโ†’A10Bโ†’A100Bโ†’A1001Bโ†’A1001 โ†’1001
ii) 00011
Answer:
Leftmost: Sโ†’A1Bโ†’0A1Bโ†’00A1Bโ†’000A1Bโ†’0001Bโ†’00011Bโ†’00011
Rightmost: Sโ†’A1Bโ†’A11Bโ†’A11 โ†’A011 โ†’A0011 โ†’A00011 โ†’00011
c) Give the parse trees for the strings in part b).
i) Answer:
1
pf3

Partial preview of the text

Download Discussion Material for CMSC330: Grammar and Parsing (10/1) and more Assignments Programming Languages in PDF only on Docsity!

CMSC330: Discussion Material (10/1)

October 1, 2008

  1. What langage does the following grammar generate:

S โ†’ aSbS | bSaS | 

Answer: The set of all strings with an equal number of aโ€™s and bโ€™s.

a) Give the grammar that generates the language of the regular expression: 01(0 | 1) Answer:

S โ†’ A 1 B A โ†’ 0 A |  B โ†’ 0 B | 1 B | 

b) Give the leftmost and rightmost derivations of the following strings using the grammar from part a):

i) 1001 Answer: Leftmost: S โ†’ A 1 B โ†’ 1 B โ†’ 10 B โ†’ 100 B โ†’ 1001 B โ†’ 1001 Rightmost: S โ†’ A 1 B โ†’ A 10 B โ†’ A 100 B โ†’ A 1001 B โ†’ A 1001 โ†’ 1001

ii) 00011 Answer: Leftmost: S โ†’ A 1 B โ†’ 0 A 1 B โ†’ 00 A 1 B โ†’ 000 A 1 B โ†’ 0001 B โ†’ 00011 B โ†’ 00011 Rightmost: S โ†’ A 1 B โ†’ A 11 B โ†’ A 11 โ†’ A 011 โ†’ A 0011 โ†’ A 00011 โ†’ 00011

c) Give the parse trees for the strings in part b).

i) Answer:

ii) Answer:

  1. Design a context free grammar for the following language: {aibj^ ck^ | i 6 = j or j 6 = k} Answer: S โ†’ RC | AT R โ†’ aRb | X X โ†’ aA | bB T โ†’ bT c | Y Y โ†’ bB | cC A โ†’ aA |  B โ†’ bB |  C โ†’ cC | 

Note: The important productions rules here are for the symbols R and T. R enforces the constraint i 6 = j and T enforces the constraint j 6 = k. The start symbol just ensures that one or the other must be true for the string to be in the language of this grammar.

  1. Given the following grammar: S โ†’ aS | aSb | 

a) Is this grammar ambiguous? Why? Answer: Yes. The string aab has two parse trees, leftmost derivations, and rightmost derivations.

b) Redesign the grammar to be unambiguous. Answer: S โ†’ aSb | A A โ†’ Aa | 

Note: This is the grammar for the language ambn^ | m โ‰ฅ n

  1. Construct a NFA for the following grammar:

S โ†’ aA | B A โ†’ aaB B โ†’ bB | a