Exercise 1: try to define a BNF definition for a greeting: “Hello, John!”, where ‘John’ can be any name starting with an uppercase character, followed by some lowercase ones.
Answer:
- lccharacter ::= a | b | c | d | e | f | … | z
- uccharacter ::= A | B | C | D | F | … | Z
- lcseq ::= lccharacter | lccharacter lcseq
- name ::= uccharacter lcseq
- greeting ::= “Hello, ” name “!”
Obviously, you could have chosen other names. Notice the “” in the greeting definition. This stresses the fact these constant words are not part of the metalanguage.
Exercise 2: write a BNF definition for a standard printf-style function, which accepts string (”%s”) and integer (”%d”) values. The formatting string can consist of any alphanumeric character, spaces and formatters. Variable names can consist of any alphanumeric character, but can’t start with a number.
Answer:
- charseq ::= lcchar | ucchar | lcchar charseq | ucchar charseq
- varname ::= charseq | charseq digits | charseq digits varname
- formatter ::= “%d” | “%s”
- word ::= lcchar | ucchar | digit | lcchar word | ucchar word | digit word
- part ::= formatter | word | ” “
- spaced ::= part | ” ” part | part ” ” | ” ” part ” “
- arg ::= spaced | spaced spaced
- varlist ::= varname | varname “, ” varname | varname “, ” varlist
- optarglist ::= “” | “, ” varlist
- printf ::= “printf(” arg optarglist “);”
This one might look somewhat big, and maybe the rule names weren’t that well-chosen, sorry about that, but you should be able to recognize some parts.
Disclaimer: I just wrote down these by hand, there might be some mistakes in them.
Pages: 1 2














12 Responses to “Text parsing, formal grammars and BNF introduction”
Leave a comment