What are general tips for generating grammars for context free languages

context-free-grammarformal-languagesintuitionregular-languagesoft-question

Perhaps, this does not have a "correct" answer, but what are general tips for creating context free grammars for context free languages? I know there is usually no step by step solution to generate these grammars, but there must be some general tips to guide one to create them.

If you are keen on explaining by example, this is the language I am having trouble with:

$
L = \{0^p1^q0^r1^s : p + q = r + s \}
$

I am not interested in the grammar to the above language, rather, I am interested in the process of creating grammars.

Best Answer

I suggest starting with a high level description of the language.

edit: I used this language instead of the language in the question. $L=\{0^p1^q0^r1^s:p+r=q+s\}$

For example with L as defined above I would describe the language as "all bitstrings with equal number of 0s and 1s such that if partitioned into the longest substrings of all 0s and longest substrings of all 1s will have a maximum of 4 partitions, and if the bitstring is partitioned into 4 substrings, then the first substring must be 0s."

From there you can choose to build the language either top down or bottom up. It's not always clear which of those two options is easiest, but I often use the bottom up approach.

In the bottom up approach you start with a base case or with base cases. So here you would use the empty string as your base case.

$T\rightarrow\lambda$

Then you would consider what you could do to build out more of the language while staying within the confines of the language.

$Q\rightarrow SRS$

$R\rightarrow1R0|T$

$S\rightarrow0S1|T$

$T\rightarrow\lambda$

And if needed continue building upwards until you have enough to generate the entire language.

Related Question