cs193p – Assignment #2 Task #3

Add the capability to your CalculatorBrain to allow the input of variables. Do so by
implementing the following API in your CalculatorBrain …

func setOperand(variable named: String)

This must do exactly what you would imagine it would: it inputs a “variable” as the operand (e.g. setOperand(variable: “x”) would input a variable named x). Setting the operand to x and then performing the operation cos would mean cos(x) is in your CalculatorBrain.

As you might have seen form the previous tasks – the tasks of this assignment are not that easily separable. Let’s start by adding two new types to operation structure. One for operands and one for variables:

    private enum Operation {
        case operand(Double)
        case variable(String)

And create a stack of those operation to do something with later on:

    private var stack = [Operation]()

Finally add the new api method which just puts the variable on the stack:

    mutating func setOperand(variable named: String) {

The change of the structure breaks the switch statement. So for now, a quick fix:

    mutating func performOperation(_ symbol: String) {
            default: break // nothing to do for operands and variables

The complete code for the assignment #2 task #3 is available on GitHub.


Leave a Reply

Your email address will not be published.