Homework 3

Questions 1

Recall that for Homework 2 we defined the language of set expressions as follows:

  1. A hash-separated list of zero or more countries enclosed in curly braces is a set expression.

  2. If S1 and S2 are both set expressions, then so are each of the following: S1 ∪ S2
    S1 ∩ S2
    S1 + S2
    ( S1 )

In a set expression, parenthesis has the highest precedence; intersection and union have the same, second highest precedence; addition has the lowest precedence. Intersection, union and addition are all left associative.

Below are 6 incorrect CFGs for the language of set expressions. For each CFG, do one of the following:

  1. Give one string that is a legal set expression (given our definition above), but is not in the language of the CFG.
  2. Give one string that is not a legal set expression (given our definition above), but is in the language of the CFG.
  3. Show that the CFG is ambiguous by drawing two different parse trees for some string in the language of the CFG.

For cases (a) and (b), be sure to say which of the two cases you are illustrating.

Note that the terminals are LPAREN, RPAREN, PLUS, UNION, INTERSECT, LCURLY, RCURLY, HASH and COUNTRY.

CFG 1:

exp → LCURLY RCURLY | LCURLY list RCURLY | term
term → term PLUS factor | factor
factor → factor UNION set | factor INTERSECT set | set
set → LPAREN set RPAREN | exp
list → COUNTRY | list HASH COUNTRY

CFG 2:

exp → exp PLUS term | term
term → term UNION factor | term INTERSECT factor | factor
factor → LPAREN factor RPAREN | LCURLY list RCURLY
list → ε | nlist
nlist → COUNTRY | nlist HASH COUNTRY

CFG 3:

exp → exp PLUS term | term
term → term UNION factor | term INTERSECT factor | factor
factor →  LPAREN exp RPAREN | LCURLY list RCURLY
list → ε | COUNTRY | list HASH COUNTRY

CFG 4:

exp → exp PLUS term | term
term → term UNION factor | term INTERSECT factor | LPAREN exp RPAREN | factor
factor → LCURLY RCURLY | LCURLY list RCURLY
list → COUNTRY | list HASH COUNTRY

CFG 5:

exp → LPAREN exp RPAREN | term
term → term PLUS factor | factor
factor → factor UNION set | factor INTERSECT set | set
set → LCURLY RCURLY | LCURLY list RCURLY
list → COUNTRY | list HASH COUNTRY

CFG 6:

exp → exp PLUS term | term
term → term UNION factor | factor INTERSECT factor | factor
factor → LPAREN exp RPAREN | LCURLY RCURLY  | LCURLY list RCURLY
list → COUNTRY | list HASH COUNTRY

Question 2:

This question concerns the following grammar.

program -> { stmts } EOF
stmts ->  stmt  stmts 
       | ε
stmt -> ID = exp ; 
      | IF ( exp ) stmt 
exp -> ID tail
tail -> + exp 
      | - exp 
      | ε

Compute the FIRST and FOLLOW sets for the non-terminals of this grammar.