CS 119 Lab 6 - Trees

Objectives

  • Become familiar with processing of trees
  • Complete parser for arithmetic infix expressions
  • 1. We wish to parse an arithmetic infix expression. This means that we are translating the expression into a tree representing the computation. The infix expression is represented as a list. For example ‘(4 + 3 * 7 - 14 / ( 3 + 4) + 6).

    Each element of the list must be one of three things: a number; one of the four symbols +, -, *, or /; or a sublist such as (3 + 4) in this example.

    What makes this problem tricky is that we can’t put the list elements into an expression tree as soon as we see them, but must instead consider the precedence of the operators. As we examine the expression from left to right, we must maintain information about the elements that have been examined but not entirely processed. We will do this in two lists: one list for still pending operations and another for still pending operands. The operand list will contain subtrees ready to be combined later on.

    Here is the algorithm:

    1. If we process a number, we turn it into a node of a tree and place it in front of the operand list.
    2. If we process an operation symbol, we test to see if it is of higher or lower precedence from the last operation symbol not yet processed. If it is higher then we can’t process it yet so that symbol goes in the front of the operator list. If it is of lower precedence then we may build the subtree with the operator at the front of the operator list and the two operands at the front of the list. This subtree then goes on the front of the operand list.
    3. If we process a sublist, we simply perform the parse recursively and place the resulting tree on the operand list.
      1.  

    Assignment:
    Consider the incomplete code in the file lab6.scm. Complete this code and try parsing the infix expression in the example. Look at the output and verify that it represents the parse tree correctly.

    2. We now can use the parse tree to perform the computation. This should be quite simple. If the entry in the tree is a number then that is the value of the computation. Otherwise, if the entry is an operator, recursively compute the value of the two subtrees and then perform the appropriate operation on those values.

    Assignment:
    Write the function compute which takes as its argument an expression tree and returns the resulting value of the expression. Be sure you maintain your abstraction barriers!

    3. Email your files containing the assignments to jzimmerm@goucher.edu.