$29
CS314
Assignment 2
1 Finite State Automaton (FSA)
(a) Specify a DFA using a transition diagram and a formal FSA specification <S, s, F, T (see lecture 2) that recognizes the following language:
“All strings of 0’s and 1’s that, when interpreted as a binary number,
are divisible by 4. In other words, value(binary number) modulo 4 =
0.”
(b) Specify a DFA using a transition diagram and a formal FSA specification <S, s, F, T (see lecture 2) that recognizes the following language:
“All strings of 0’s and 1’s that, when interpreted as a binary number,
its value modulo 4 = 1. ”
2 Context-Free Languages
Are the following languages context-free or not? If yes, specify a contextfree grammar in BNF notation that generates the language. If not, give an
informal argument.
(a) { a
mb
n
c
o
| m n ≥ 0, o 0} , with alphabet Σ = {a, b, c}
(b) { a
n
b
3n
| n ≥ 0 }, with alphabet Σ = {a, b}
(c) { wwR | w ∈ Σ
∗ and w
R is w in reverse }, with alphabet Σ ={a, b}
(d) { a
n
b
n
c
nd
m | n ≥ 0, m ≥ 0 }, with alphabet Σ = {a, b, c, d}
(e) { w | w has no more than 3 symbols}, with alphabet Σ={a, b}
3 Derivation, Parse Tree, Ambiguity, Precedence & Associativity
A language that is a subset of the language of propositional logic may be
defined as follows:
1
<start ::= <expr
<expr :: = <expr ∨ <expr |
<expr ∧ <expr |
<expr → <expr |
<const | <var
<const :: = true | false
<var :: = a | b | c | . . . | z
(a) Give a leftmost and a rightmost derivation for the sentence
a ∨ false ∧ b → false .
(b) Give the corresponding parse trees for the derivations.
(c) Give the corresponding abstract syntax tree (AST).
(d) Show that the above grammar is ambiguous.
(e) Give an unambiguous grammar for the same language that enforces the
following precedence and associativity:
• ∧ has highest precedence (binds strongest), followed by ∨, and
then →
• ∧ and ∨ are left associative, and → is right associative
(f) Give the parse tree and AST for your new, unambiguous grammar for
the sentence
a ∨ true ∧ b → false ∨ true .
4 Extra-credit Problem — Fix the grammar
for dangling if-then-else statement (10% more
points)
Recall the simple statement grammar we discussed in class:
2
<start ::= <stmt
<stmt ::= <if-stmt | <assgn
<if-stmt ::= if <expr then <stmt |
if <expr then <stmt else <stmt
<assgn ::= <id := <d
<expr ::= <id = 0
<d ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<id ::= a | b | c | . . . | z
The above grammar will cause ambiguity for parsing the following compound statement:
if x = 0 then if y = 0 then z := 1 else z := 2
Is it possible to change the grammar without changing the language
to parse the above statement unambiguously? If not, please give an informal argument. If yes, please provide your solution. Note that you are not
supposed to add new terminals (tokens), i.e., delimiters, as it will change the
language.
3