| 1 |
An optional series of elements, separated from each other using delimiters |
| 2 |
occurs frequently in programming languages. For example, bf(C++) functions |
| 3 |
have parameter lists which may or may not require arguments. Since a parameter |
| 4 |
list may be defined empty, an em(empty) alternative is required. However, a |
| 5 |
simple generalization of the optional series construction (section |
| 6 |
ref(OPTSERIES)) won't work, since that would imply that the em(first) argument |
| 7 |
is preceded by a separator, which is clearly not the intention. So, the |
| 8 |
following construction is em(wrong): |
| 9 |
verb( |
| 10 |
opt_parlist: |
| 11 |
// empty |
| 12 |
| |
| 13 |
opt_parlist ',' parameter |
| 14 |
) |
| 15 |
To define an optional series of delimited elements em(two) rules are |
| 16 |
required: one rule handling the optional part, the other the delimited series |
| 17 |
of elements. So, the correct definition is as follows: |
| 18 |
verb( |
| 19 |
opt_parlist: |
| 20 |
// empty |
| 21 |
| |
| 22 |
parlist |
| 23 |
; |
| 24 |
|
| 25 |
parlist: |
| 26 |
parameter |
| 27 |
| |
| 28 |
parlist ',' parameter |
| 29 |
; |
| 30 |
) |
| 31 |
Again, the above rule pair can be used as a prototype for recognizing an |
| 32 |
optional series of delimited elements. The generic form of these rules could |
| 33 |
be formulated as follows: |
| 34 |
verb( |
| 35 |
opt_series: |
| 36 |
// empty |
| 37 |
| |
| 38 |
series |
| 39 |
; |
| 40 |
|
| 41 |
series: |
| 42 |
element |
| 43 |
| |
| 44 |
series delimiter element |
| 45 |
) |
| 46 |
Note that the tt(opt_series) rules neatly distinguishes the no-element |
| 47 |
case from the case were elements are present. Usually these two cases need to |
| 48 |
be handled quite differently, and the tt(opt_series) rules empty alternative |
| 49 |
easily allows us to recognize the no-elements case. |