简体   繁体   中英

Is there a better way to write a right-recursive grammar's production rules than this?

Scenario: Give production rules for a RIGHT-recursive grammar that describes the set of all non-empty strings made from the characters R and N, which may contain arbitrarily many contiguous repetitions of R, but precisely two or precisely three contiguous repetitions of N.

Answer:

A -> NB | R + A

B -> ND | NC | N ε

C -> ND | N ε

D -> R + D | R ε

Incorrect:

A -> NNB | NNNB | RA | R
B -> R | RA | ε

edit: the above is not correct, I misunderstood the scenario.

Correct:

S -> RS | A
A -> NA | NB
B -> RB | RC
C -> NC | ND
D -> RD | RE | ε
E -> NE | NF
F -> RF | ε

How it works: It starts with S, that can generate 0 or more R or move to A, which generates the first group of Ns. Then it moves to B, which generates the Rs between 1st and 2nd group of Ns. Then it move to C, which generates the 2nd group of Ns. Then it moves to D, which can generate 0 or more Rs and either finish or move to E, which generates the 3rd group of Ns. Lastly it moves to F, which generates 0 or more Rs.

This works just as well and is simpler:

S -> RS | A
A -> NA | NB
B -> RB | RC
C -> NC | ND
D -> RD | E
E -> NE | F
F -> RF | ε

It is the same up to D where instead of providing an ε option it provides an option to add another group of R's or go to E which is another group of N's, but this would not occur if there were no R's previously anyway as they would have been outputted as a conversion from C, and then another option to recursively add R's or an empty string.

Example parse tree generated from the input NRNR

S
  \
   A
  / \
 N   B
    / \
   R   C
      / \
     N   D
        / \
       R   D
            \
             E
              \
               F
                \
                 ε

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM