1

Imagine we have a Context Free Grammer, CFG, as follows:

S -> a ...(1)

S -> SS ...(2)

And i derive a string in the specified language as follows:

S ..start state

SS ..using (2)

aS ...using (1) <- is this valid, like only applying the subsititution rule on 1 variable instead of all same variables?

So my question is if i were to apply rule (1) on "SS", do i have the option to apply (1) to only 1 S of the "SS" or do i have to apply to both of them?

1 Answers1

1

You can apply the rule to only one S, or as many as you like. Here is a slightly more complicated example that maybe better illustrates the idea:

S -> a       (1)
S -> b       (2)
S -> SS      (3)

So, what strings are in this language? Here are the first few strings with derivations:

a: S -> a
b: S -> b
aa: S -> SS -> aS -> aa
    S -> SS -> Sa -> aa
ab: S -> SS -> aS -> ab
    S -> SS -> Sb -> as
ba: S -> SS -> bS -> ba
    S -> SS -> Sa -> ba
bb: S -> SS -> bS -> bb
    S -> SS -> Sb -> bb
aaa: S -> SS -> aS -> aSS -> aaS -> aaa
     S -> SS -> aS -> aSS -> aSa -> aaa
     S -> SS -> Sa -> SSa -> aSa -> aaa
     S -> SS -> Sa -> SSa -> Saa -> aaa
aab
...

Anyway, we find that the grammar generates all non-empty strings of a's and b's, including those with mixed up a's and b's. If we had to replace all S's with the same rule, we would get a much, much smaller language, if we'd get a (non-empty) language at all.

Patrick87
  • 27,682
  • 3
  • 38
  • 73
  • Ayy thank you! that sums it up for me, i do have one more question it's kinda stupid but i'll ask it anyways:- S -> SS -> SSS -> SaS ..(1) -> baS -> bab - (1) is legal too right? like changing the middle one first, like the location of "variable" in the string does not matter right? According to me it does not – Pratik Hadawale Apr 27 '22 at 02:33
  • Right, I probably missed an example of starting from the middle, but yes, you can "replace" any non-terminal symbol, whether at the front, middle or back, and you can choose a different production if you want each time you replace the same non-terminal symbol in different parts of the string. The non-terminal symbols are not so much "variables" in that they don't have a "value", instead, they are more like instructions for making a string and can be instructions like "insert x or y or z here". Like at a restaurant when they say pick two sides, they don't have to be the same. @PratikHadawale – Patrick87 Apr 27 '22 at 10:57
  • Thank You so much, you explain very well :) I have understood everything now – Pratik Hadawale Apr 27 '22 at 11:03