## 10.2. ` `A CFG for Arithmetic Expressions

An example grammar that generates strings representing
arithmetic expressions with the four operators

+, -, *, /,

and numbers as operands is:

1. <expression>: number
2. <expression>: ( <expression> )
3. <expression>: <expression> + <expression>
4. <expression>: <expression> - <expression>
5. <expression>: <expression> * <expression>
6. <expression>: <expression> / <expression>

The only nonterminal symbol in this grammar is <expression>,
which is also the start symbol.` `
The terminal symbols are

{ +, -, *, /, (, ), number } .` `

(We will interpret "number" to represent any valid number.)

The first rule (or production) states that an <expression>
can be rewritten as (or replaced by) a number.` `
In other words, a number is a valid expression.` `

The second rule says that an <expression> enclosed in
parentheses is also an <expression>.` `
Note that this rule defines an expression in terms of expressions,
an example of the use of recursion in the definition of context-free
grammars.` `

The remaining rules say that the sum, difference, product,
or division of two <expression>s is also an expression.` `

Created by *unroff & hp-tools.*
© by Hans-Peter Bischof. All Rights Reserved (1998).
Last modified: 27/July/98 (12:14)