Little Java Exerices 3
Practice with the Visitor Pattern

Preparation

Read through Section 1.13 in the class lecture notes.

Set Up

Create a new local folder and copy either (i) your solution to the BooleanExpression.java program from the previous set of exercises or (ii) the file teachjava.org/2002/hw/03/. This file contains the definition of a BooleanExpression class including a method eval(Environment e) for evaluating them.

Problems

  1. Define an interface IVisitor with Object as the return type for the various visitor methods (forConst, etc.) in the interface. Add an accept method to each subclass of BooleanExpression. Define an expression evaluator as a concrete class EvalVisitor implementing Visitor. Modify the test method to test the EvalVisitor class.

  2. Add a let clause to the syntax of Boolean expressions and modify IVisitor and EvalVisitor to support this new syntactic form, using the same semantics for let given in class in the context of arithmetic expressions. Modify the test method to test the revised EvalVisitor class.

  3. Roll back to the solution to Problem 1. Add an if clause to the syntax of Boolean expressions where an if has the form
    if a then b else C
    
    Use a concrete class called If to represent an if form. In the interest of brevity, the toString() method should produce the string
    (? a b c)
    
    for the expression
    if a then b else c
    
    Modify the toString methods of the other classes as follows:

    a and b prints as (^ a b)

    a or b prints as (| a b)

    a implies b prints as (> a b)

    not a prints as ~a

    true prints as T

    false prints as F

    Modify the main method to test the revised EvalVisitor class.

  4. Using the same definition of BooleanExpression and IVisitor as the solution to the preceding problem, define a visitor class ConvertVisitor extending Visitor that converts Boolean expressions to pure if form (constants, variables, and if forms). In particular:
    (& A B) --> (? A B F)
    (| A B) --> (? A T B)
    (> A B) --> (? A B T)
    ~A --> (? A F T)
    
    Modify the main method to test the ConvertVisitor class.

  5. Define a visitor class CleanVisitor that changes Boolean expressions in converted form back to conventional form. Your code should work for arbitrary Boolean expressions in pure if including those that were not produced by ConvertVisitor. Some boolean expressions may still contain if forms after deconversion. Strive for the simplest form. Hint: you will need to override the inherited definition of equals on Boolean expressions.

cork@rice.edu