So far our grammar is not practical. For example imagine being able to store numbers which can have between 1 and 200 digits.

 

<Two_Digit_Number> ::= <Digit> <Digit>

<Three_Digit_Number> ::= <Digit> <Digit> <Digit>

<Four_Digit_Number> ::= <Digit> <Digit> <Digit> <Digit>

 

This is clearly a impractical situation to be in. We need a situation where we can define any number of digits so we can simply have a single rule for numbers. Thankfully this is easy in BNF when we use recursion. Below is the recursive rule for a number of variable length of digits.

 

<Number> ::= <Digit> | <Digit> <Number>

 

What we are saying here is that we can either have a single digit or we can have a digit followed by a number. Consider 5983.

 

First of all we look at the 5. This is clearly a digit so it can match to either <Digit> or <Digit><Number>. As there is still more information after the 5 it means that we can not match the first rule. As such we go to the second rule. This calls the <Number> rule again, but for the 9. We keep doing this until we reach the end. The 3 matches the <Digit> on its own as there is no more input. Let’s look at a derivation of the above.

 

<Number> ::= <Digit> | <Digit> <Number>

<Number> ::= 5 <Number>

<Number> ::= 5 <Digit> | <Digit> <Number>

<Number> ::= 59 <Number>

<Number> ::= 59 <Digit> | <Digit> <Number>

<Number> ::= 598 <Number>

<Number> ::= 598 <Digit> | <Digit> <Number>

<Number> ::= 598 3

 

As you can see we can see that a single digit is always an number and also any collection of digits is also considered an number. If we were to write out all of the <Number> calls together we would get the following, with the last number becoming a single digit.

 

<Number> ::= <Digit> <Digit> <Digit> <Number>