SA-8, due Oct 18
Assignment
In this assignment you will add the class Negate
to the collection of classes
that implement the Expression
interface. It should
represent unary minus, which negates the Expression
referenced by
the single instance variable in the Negate
class. That is, its eval
method should call eval
on its expression (its unary operand) and
then return the negation
of the result. If the operand evaluates to 6, eval
should return -6.
If the operand evaluates to -5, eval
should return 5. Also,
the derivative of a Negate
will be the Negate
of
the derivative of its expression.
A unary minus
will let us represent expressions like "-x". Currently the only way to
express this would be "0-x" using the binary subtraction operation. With the
Negate
class
we could represent it by the Expression
created by calling
Negate.make(Variable.make("x"))
.
You need to modify and add to my code, all of which you can get
by downloading src.zip
.
Negate
should implement the two required methods
(in the Expression
interface), along with
toString
and make
. Its constructor should be private,
like the Constructors of the classes that I provided.
After you get Negate
working you should modify the
make
methods of the other classes to take it into account.
One change that you are required to make is that all constants
be non-negative. For example, Constant.make(-6)
should return a Negate
object whose operand is a
Constant
whose value is 6. There are a number of other
changes that make sense. For instance, would you ever write:
"3 + (-x)" or "-(-x)" or "-x * (-y)"? I am not expecting you to
implement every possible simplification, but you should be able to
come up with a half dozen or so simplifications.
You should not make changes to other classes except in their
make
methods.
Extra Credit
Add other operators. You might add sin or cos or other functions. Or exponentiation. Or whatever you think would be interesting. If you do add other operators, turn in two submissions, the standard assignment and the one with your extra credit.
Blackboard submission
Test your code by modifying the main
method of ExpressionDriver.java
. Try to create a convincing set of tests.
Submit via Blackboard the zip file of a folder that contains all java files (including the ones that you didn't have to modify) and the screenshot of a test run.
Please be sure that comments in the code make it clear what changes you made.