TBO VII-chomsky Normal Form
TBO VII-chomsky Normal Form
for
Context-free Grammars
1
Chomsky Normal Forms
Theorema:
Apapun CFG G = (V, T, S, P) dengan
L(G) memiliki sebuah grammar equivalen G’
= (V’, T, S, P’) yang berbentuk Chomsky normal
form.
Chomsky Normal Form
A BC or Aa
3
Examples:
S AS S AS
S a S AAS
A SA A SA
Ab A aa
Chomsky Not Chomsky
Normal Form Normal Form
4
Chomsky Normal Forms
Asumsi: G tidak memiliki:
- production
Unit-production
Langkah 1
Buat sebuah grammar G1 = (V1, T, S, P1) dari G
dengan bentuk produksi pada P :
A x1x2x3…xn (1)
dimana Ci Vi
Chomsky Normal Forms
Langkah 2
Meletakkan semua produksi dengan format
(2), dan juga (3) jika n 2, ke P1.
Vn-2 Cn-1Cn
Convertion to Chomsky Normal Form
Example: S ABa
A aab
B Ac
Not Chomsky
Normal Form
9
Introduce variables for terminals: Ta , Tb , Tc
S ABTa
S ABa A TaTaTb
A aab B ATc
B Ac Ta a
Tb b
Tc c
10
Introduce intermediate variable: V1
S AV1
S ABTa
V1 BTa
A TaTaTb
A TaTaTb
B ATc
B ATc
Ta a
Ta a
Tb b
Tb b
Tc c
Tc c
11
Introduce intermediate variable: V2
S AV1
S AV1
V1 BTa
V1 BTa
A TaV2
A TaTaTb
V2 TaTb
B ATc
B ATc
Ta a
Ta a
Tb b
Tb b
Tc c
Tc c 12
Final grammar in Chomsky Normal Form:
S AV1
V1 BTa
A TaV2
Initial grammar
V2 TaTb
S ABa B ATc
A aab Ta a
B Ac Tb b
Tc c 13
Observations
14
Greinbach Normal Form
A a V1V2 Vk k 0
symbol variables
15
Observations
16
Compilers
17
Machine Code
Program Add v,v,0
v = 5; cmp v,5
if (v>5) jmplt ELSE
x = 12 + v; THEN:
while (x !=3) { Compiler
add x, 12,v
x = x - 3; ELSE:
v = 10; WHILE:
} cmp x,3
...... ...
18
Compiler
Lexical
parser
analyzer
input output
machine
program
code
19
A parser knows the grammar
of the programming language
20
Parser
PROGRAM STMT_LIST
STMT_LIST STMT; STMT_LIST | STMT;
STMT EXPR | IF_STMT | WHILE_STMT
| { STMT_LIST }
21
The parser finds the derivation
of a particular input
derivation
Parser
input E => E + E
E -> E + E
=> E + E * E
10 + 2 * 5 |E*E
=> 10 + E*E
| INT
=> 10 + 2 * E
=> 10 + 2 * 5
22
derivation tree
derivation
E
E => E + E E + E
=> E + E * E
=> 10 + E*E 10
E * E
=> 10 + 2 * E
=> 10 + 2 * 5 2 5
23
derivation tree
E machine code
E + E mult a, 2, 5
add b, 10, a
10
E * E
2 5
24
Parsing
25
Parser
input
grammar derivation
string
26
Example:
Parser
S SS derivation
input
S aSb
aabb ?
S bSa
S
27
Exhaustive Search
S SS | aSb | bSa |
29
Phase 2 S SS | aSb | bSa |
S SS SSS
S SS aSbS aabb
Phase 1 S SS bSaS
S SS S SS S
S aSb S aSb aSSb
S aSb aaSbb
S aSb abSab
S aSb ab 30
S SS | aSb | bSa |
Phase 2
S SS SSS
S SS aSbS aabb
S SS S
S aSb aSSb
S aSb aaSbb
Phase 3
S aSb aaSbb aabb
31
Final result of exhaustive search
(top-down parsing)
Parser
S SS
input
S aSb
aabb
S bSa
S
derivation
A
A B
Number of phases for string w : approx. |w|
33
For grammar with k rules
k possible derivations
34
Time for phase 2: k 2
k 2 possible derivations
35
Time for phase |w| is 2|w|:
36
Total time needed for string w:
k k k
2 | w|
Extremely bad!!!
37
For general context-free grammars:
38