0

How can I construct an LR($k$) grammar (which $k$ is not really of interest for now) for a given language, say:

$$L=\left\{w \in \{a, b\}^\star \ | \ \exists u \in \{a, b\}, v \in \{a, b\}^\star: w = vu \wedge |w|_u \operatorname{mod} 2 = 0\right\}$$

($|w|_u$ denotes the number of $u$'s in $w$).

Please note that I don't want a right or left linear grammar although I KNOW that the language is regular. I am interested in the process of creating an LR($k$) grammar for an arbitrary, in general more complex language. (Feel free to ignore this example.)

Gilles 'SO- stop being evil'
  • 44,159
  • 8
  • 120
  • 184
lukas.coenig
  • 773
  • 4
  • 12

1 Answers1

1

You question is very strangely stated. The answer is however very trivial. Your language $L$ is a regular language, hence recognizable by a DFA. It does not even need a pushdown stack. Hence it has to be LR(k). Indeed, the lookahead is necessary only to make the recognition deterministic, but in this case, it is deterministic to start with if you use the DFA (this is a bit tautological, since building the LR parser involve in general building a DFA, if my memory does not fail me)

You can get the LR grammar (if one dares calling it that, trivial as it is) just by taking the right-linear grammar corresponding to the transitions of the DFA.

BTW, it is not easy to decide whether a given grammar is LR(k) for some unknown k, it is undecidable. But it is decidable when k is given, you just try to build the tables.

To answer your question about a procedure to build a LR(k) grammar for a given CF language, the answer is "sorry: not in this universe".

The reason is that it is undecidable whether a given CF language is deterministic or not. Since any deterministic CF language has a LR(k) grammar, if a procedure existed to produce a LR(k) grammar for a language, when possible, that would be a procedure to decide whether the language is deterministic. Since no such procedure can exist, we have no systematic way of obtaining an LR(k) grammar for the language.

babou
  • 19,645
  • 43
  • 77