Context-Free Grammar suggestions for unary subtraction?

后端 未结 2 349
天涯浪人
天涯浪人 2021-01-24 07:24

L = {1i - 1j = 1i-j: i-j >= 0, i,j>=0}

I\'m confused about how to construct a grammar that tracks subtraction of a stri

2条回答
  •  借酒劲吻你
    2021-01-24 07:42

    Here's a tip: always try to think of context-free languages in terms of parenthetic balancing.

    Consider the following two languages:

    ab             ()
    aabb          (())
    aaabbb       ((()))
    aaaabbbb    (((())))
    ...            ...
    

    Most of us "see" the first language as a repetition (some a's followed by the same number of b's) and the second one as a nesting. But the context-free grammars for these two languages are identical:

    S: ab       S: ()
     | a S b     | ( S )
    

    Because the CFG is being parsed with a stack automaton, the nesting is natural. The first language is actually some number of a's followed by the same number of b's, reversed. Of course, some number of b's and some number of b's reversed look identical... until you draw the derivation tree.

    So consider the unary addition language: { 1i+j = 1i + 1j }.

    Clearly that's the same as { 1j+i = 1i + 1j } (switching the order of addition makes no difference). Or, writing out the addition as a simple concatenation: { 1j 1i = 1i + 1j }. Now, we can just group the symmetry: (here the parentheses are metasymbols to show grouping, not part of the language): { 1j ( ( 1i = 1i ) + ) 1j }.

    Which leads to

    L1 → =
    L1 → 1 L1 1
    L2 → L1 +
    L2 → 1 L2 1

    In the CFG, the addition has been obscured a bit, but it's clear what is happening: we're allowing a sentence with the same number of 1s on both sides of an =, with a single + being inserted anywhere on the right-hand side. (With a very simple change to the grammar, we could allow multiple + signs, making out grammar accept addition equations with more than one addend.)

提交回复
热议问题