|
| |
Abstract Syntax Trees
Part B: Adding More Node Types
Requirement:
For Part B, consider all the classes you developed in Part A locked.
This means that you cannot add or
change anything in those files. Of course, if
you find this rule impossible to abide by, then you probably didn't
implement Part A correctly, or perhaps you don't understand
something. If the latter, don't hesitate to ask questions!
Create the following classes, all in package abstractSyntaxTree:
- A
Real class that will hold floating
point (double)
values. This will, like the Integer
class, be a leaf class in the abstract syntax tree.
- A
UnaryPlus class. This, of course, will
look very similar to the UnaryMinus
class.
- A
Minus class. This, of course, will
look very similar to the Plus
class.
- A
DividedBy class. This, of course,
will look very similar to the Times
class.
Here's an enhanced Tree
class to test your work:
package abstractSyntaxTree;
/**
* A class to represent an Abstract Syntax Tree.
* <p>
* @author: Bryan J. Higgs, 5 September 1998
* <p>
* @version 1.0
*/
public abstract class Tree
{
public static void main(String[] args)
{
Node expression =
new Plus(
new UnaryMinus(
new Integer(5)
),
new Times(
new Integer(12),
new Integer(4)
)
);
double result = expression.evaluate();
System.out.print("Result of ");
expression.walk();
System.out.println(" = " + result);
expression =
new Minus(
new DividedBy(
new Real(53.5),
new Integer(45)
),
new Times(
new Real(73.54),
new Plus(
new UnaryPlus(
new Integer(3)
),
new Integer(8)
)
)
);
result = expression.evaluate();
System.out.print("Result of ");
expression.walk();
System.out.println(" = " + result);
expression =
new Times(
new Minus(
new Real(53.5),
new Integer(45)
),
new Plus(
new Real(73.54),
new Plus(
new UnaryMinus(
new Integer(3)
),
new Integer(8)
)
)
);
result = expression.evaluate();
System.out.print("Result of ");
expression.walk();
System.out.println(" = " + result);
}
}
|
When you have completed the additional classes, build this new
Tree class and
run it to get the results of the three expressions. (Cut the
above code from this webpage and paste it into your editor.)
Note:
You may notice that the second and third expressions in the
above class are not correctly parenthesized when printed.
Don't worry about that for now; we'll fix that later, in Part
C.
How hard was it to add these classes?
What did you learn from this
exercise?
|