Fundamentals of Computer Science II (CSC-152 97F)

[News] [Basics] [Syllabus] [Outlines] [Assignments] [Examples] [Readings] [Bailey Docs]

# Outline of Class 39: Expressions, Revisited

## Miscellaneous

• I made some changes to the outline of the previous class directly after the class.
• As I mentioned in an email message, I've also made some more modifications to the outline of Monday's class to incorporate our unplanned discussion.
• Few of you have turned in the most recent homeworks. Please let me know when they're done.

## Expression Trees, Continued

• Recall that it is convenient to represent expressions as trees because
• It eliminates the need for parentheses.
• It eliminates the need for precedence.
• It supports operations with more than two arguments.
• It clarifies the meaning of the expression.
• It makes evaluation easier.
• Today, we'll think more about the implementation of expression trees.

### Implementing Expression Trees

• We might begin to write a Java class to support such trees with
/** A tree-based representation of expressions  */
public class ExpressionTree {
// ---------- Constants ----------
/** Indicate that a node contains an operation. */
public static final int OPERATION = 32;
/** Indicate that a node contains a variable. */
public static final int VARIABLE = 42;
/** Indicate that a node contains an integer. */
public static final int INTEGER = 52;

// ---------- Fields ----------
/** The contents of the current node. */
private Object contents;
/** The arity of the operation (for operation nodes). */
private int arity;
/** The arguments (if there are any). */
private ExpressionTree[] arguments;
/** The "type" of information stored in the current node. */
int type;
...

// ---------- Constructors ----------
/** Create a leaf node with one integer value. */
public ExpressionTree(int val) {
contents = new Integer(val);
arity = 0;
arguments = null;
type = INTEGER;
} // ExpressionTree
/** Create a binary expression. */
public ExpressionTree(
Operation op,
ExpressionTree arg0,
ExpressionTree arg1)
{
contents = op;
type = OPERATION;
arity = 2;
arguments = new ExpressionTree[2];
arguments[0] = arg0;
arguments[1] = arg1;
} // ExpressionTree
/** Create a trinary expression. */
public ExpressionTree(
Operation op,
ExpressionTree arg0,
ExpressionTree arg1,
ExpressionTree arg2)
{
...
} // ExpressionTree(op,ETree,Etree,Etree)
...
} // ExpressionTree

• Of course, it would be better to represent the arguments with a vector, but this provides a slightly easier implementation.

Outlines: prev next

[News] [Basics] [Syllabus] [Outlines] [Assignments] [Examples] [Readings] [Bailey Docs]

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.