This tutorial covers:
The following are examples of integer arithmetic expressions:
The question is how can we write a program to evaluate such expression? The first step is to define appropriate classes to represent these expressions. This requires knowing the rules that define integer arithmetic expressions. Here are the grammar rules:
These rules constitute what is called the defining "grammar" for the
"language" of integer arithmetic expressions. ArithExpression,
ConstExpression, SumExpression, ProdExpression, NegExpression are called the non-terminal
symbols of the grammar. ArithExpression is a special non-terminal called the start
symbol. int, +, *, -
constitute the terminal symbols. Evaluating an integer arithmetic
expression defined by the above grammar is an example of what is called "interpreting
a language." There is a well-known OO design solution to the problem of
language interpretation. It is called the interpreter pattern! In
this pattern, we represent the above grammar by defining a class for each of the non
terminal symbols. The start symbol is defined as an abstract class with all of the
other classes as its sublcasses. We then add a method generically called interpret
for each class to do the job of interpreting! Applying the interpreter pattern to
our grammar gives the following class diagram in UML. Notice that
the eval
method is the generic interpret
method.
Exercises:
If time permits, your labbies will explain the soultions to the homework #1.
D. X. Nguyen, Sept. 16, 1999. dxnguyen@cs.rice.edu