Context Free Grammar for integers

7.7k Views Asked by At

Construct Context-free Grammar for integers. Integer can begin with + or - and after that we have non-empty string of digits. Integer must not contain unnecessary leading zeros and zero should not be preceded by + or -. For example: 0; 123; -15; +9999 are correct, but +0; 01; +-3; +09; + are incorrect.

I have something like this:

(number) ::= (unsigned number) | (sign)(unsigned number)

(sign) ::= + | –

(unsigned number) ::= (digit) | (unsigned number)(digit)

(digit) ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |

| - or

Is it okay? ;)

2

There are 2 best solutions below

0
On

No.

Your syntax allows +0, 01, and +09. Try this instead

(number) ::= 0 | (nonzero unsigned number) | (sign)(nonzero unsigned number)

(sign) ::= + | -

(nonzero unsigned number) ::= (nonzero digit)(digits)

(nonzero digit) ::= 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

(digit) ::= 0 | (nonzero digit)

(digits) ::= | (digits)(digit)

0
On

HINT: It’s a good start, but it doesn’t quite work: it allows signed $0$ and unsigned integers with leading zeroes. I’d treat $0$ separately:

$$\text{(number)}::=0\mid\text{(non-zero number)}$$

Then you can do something similar to what you have:

$$\text{(non-zero number)}::=\text{(unsigned number)}\mid\text{(sign)}\text{(unsigned number)}$$

Finally, you need to make sure that the first digit of $\text{(unsigned number)}$ is not $0$. Try adding identifiers $\text{(first digit)}$ and $\text{(rest)}$ and expressing $\text{(unsigned number)}$ in terms of them.