TITLE: Proving Grammar Correctness
QUESTION [5 upvotes]: I'm having difficulties in proving the correctness of grammars. The following problem and my pity attempt to solve it show that I may not understand even the basics of such proofs. Very frutstrating....
Could someone point me to the right direction?
The text book used in my class is "Introduction to Automata Theory, Languages, and Computation (2nd Edition) by John Hopcroft". It contains just a very brief description of how to handle such proofs on page 179, in the box "The Form of Proofs About Grammars". He uses a language of palindromes as example, which is much easier than the following problem (IMHO).
Is there any place where I can find examples of grammar proofs?
Thanks!  .. and here is the problem:
"Let L be the language on ({a,b}), of all strings with an equal number of 'a' and 'b'.
$S \to \epsilon | aB | bA $
$A \to aS | bAA$
$B \to bS | aBB$
Prove that G generates language L. "
$\forall w, G\overset{*}{\Rightarrow }w \Leftrightarrow  |w|_a=|w|_b$
Proving the left side by induction on the number of derivation steps and the right side on the length of  w
Basis: 
Left side (one derivation step):
$G\overset{*}{\Rightarrow }\epsilon $
$|\epsilon |_a=|\epsilon |_b$
Right Side (length of w is 0):
$|\epsilon |_a=|\epsilon |_b$ 
$G\overset{*}{\Rightarrow }\epsilon $
Induction:
Right Side (length of w is n+1)
w=sa             (a is one symbol and |s|=n)
$|s|_a=|s|_b$    (inductive hypothesis) 
$G\overset{*}{\Rightarrow}s\overset{*}{\Rightarrow }sa$
I can't go ant further... :(

REPLY [2 votes]: To show that each word that can be produced by the grammar $G$ contains an equal number of 'a' and 'b' prove by induction that at every step the number of 'a' plus the number of 'A' equals the number of 'b' plus the number of 'B'. Note that the initial word $S$ has this property and that it is preserved by any of the production rules. Since the resulting word cannot contain the non-terminal symbols 'A' and 'B' it must contain an equal number of 'a' and 'b'.
For the reverse inclusion, let $w$ be a word that contains an equal number of 'a' and 'b' and use induction by the word length to show that $w$ can be produced by $G$. If $w$ is the empty word, just use the rule $S \rightarrow \varepsilon$. Otherwise, $w$ must contain either $ab$ or $ba$ as a substring, w.l.o.g. let $w = uabv$ for some words $u$ and $v$. Then $uv$ contains an equal number of 'a' and 'b', hence it can be produced in $G$ by the induction hypothesis. In a left derivation of $uv$, there must be some intermediate word $uXy$ where $X$ is a non-terminal symbol, i.e. $X \in \{S,A,B\}$. By the given rules, it is possible to derive $abX$ from $X$ (for example $A \Rightarrow aS \Rightarrow abA$, similarly for $B$ and $S$). So you can derive $uabXy$ in $G$. Then go on as in the derivation of $uv$ to get a derivation of $w = uabv$.