Assignment 7: Visitors
Goals: To practice using the visitor patterns.
Instructions
As always, be very careful with your naming conventions. You should not use mutation on this problem.
Due Date: Monday, June 2nd at 9:00pm
Problem 1: Visitors
+-------------------+ | IArith | +-------------------+ +-------------------+ /_\ /_\ | |---------------------------------------------------------------- | | | +-------------+ +------------------------------+ +------------------------------------------+ | Const | | UnaryFormula | | BinaryFormula | +-------------+ +------------------------------+ +------------------------------------------+ | double num | | Function<Double,Double> func | | BiFunction <Double, Double, Double> func | +-------------+ | String name | | String name | | IArith child | | IArith left | +------------------------------+ | IArith right | +------------------------------------------+
Specifically, the above represents an arithmetic expression. The Function and BiFunction in UnaryFormula and BinaryFormula respectively denote the arithmetic operation to be applied to their respective operands (child and left,right).
You must support 4 binary formulas (named "plus", "minus", "mul" and "div" representing addition, subtraction, multiplication and division respectively), and 2 unary formulas (named "neg" and "sqr" representing negation and squaring respectively).
Design an interface IArithVisitor<R> representing a visitor that visits an IArith and produces a result of type R. The visitor must be usable as a Function object on IArith producing a result of type R. For example, given an IArith object named iObj, and a SomeVisitor class, we should be able to write new SomeVisitor().apply(iObj).
Design an accept(IArithVisitor<R>) method for the IArith interface and implement it on Const, UnaryFormula and BinaryFormula.
Design an EvalVisitor that visits an IArith and evaluates the tree to a Double answer.
Design a PrintVisitor that visits an IArith and produces a String showing the fully-parenthesized expression in Racket-like prefix notation (i.e. "(div (plus 1.0 2.0) (neg 1.5))"), using the name for Formulas and using Double.toString(num) on Consts.
Design a MirrorVisitor that visits an IArith and produces another IArith, where every BinaryFormula in the tree has switched its left and right fields.
Design an AllEvenVisitor that visits an IArith and produces a Boolean that is true if every constant in the tree is even.