TITLE: Context free grammar for language { {a,b}*: where the number of a's = the number of b's}
QUESTION [8 upvotes]: My professor said that converting a language to a CFG is more of an art than anything else. I looked at this problem and didn't even know how to get started, or how I would reason my way to the solution (which I understand how it is correct).
Are there any useful patterns to deal with these conversions?

REPLY [8 votes]: If we rewrite $R$ as $\{\, S \to \epsilon, S \to SaSbS, S \to SbSaS \,\}$, it's obvious that every word produced by the CFG is in the language, because no rule causes an imbalance in the number of $a$'s and $b$'s.
In the other direction, one can use induction to show how to derive any balanced word $w$ (one with equal numbers of $a$'s and $b$'s) from $S$.  
If the length $|w|$ of $w$ is less than $2$, it's obviously possible:  There are no words of length $1$ in the language, and $\epsilon$ is produced by $S \to \epsilon$.
Otherwise we consider two cases, based on the first letter of $w$.  Suppose $w$ starts with $a$.  (The other case is symmetric.) Then
$$ S \to SaSbS \to aSbS \enspace. $$
We now have a word $u$ such that $w = au$ and $u$ has one more $b$ than it has $a$'s.  Hence it can be written as $s_1bs_2$ in such a way that each $s_i$ has the same number of $a$'s and $b$'s (and is possibly empty).  Both $s_1$ and $s_2$ are strictly shorter than $w$; hence the induction hypothesis applies to each $s_i$ and we are done.

There's more than one way to split $u$ into $s_1$, $b$, and $s_2$ so that $s_1$ and $s_2$ are balanced.  A simple one is to let $s_1$ be the longest balanced prefix of $u$.  The next letter of $u$ then necessarily exists and is a $b$; $s_2$ is whatever is left.

If we look back at the proof, we realize that the following set of rules will do:
$$\begin{align}
  S &\to \epsilon \\
  S &\to aSbS \\
  S &\to bSaS \enspace.
\end{align}$$
This illustrates the frequent usefulness of proofs beyond the obvious primary goal of establishing correctness.