cs193p – Project #2 Assignment #2 Task #6

By Stefan-Xp (Own work) [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons

Please note, this blog entry is from a previous course. You might want to check out the current one.

The evaluate() function should use a variable’s value (from the variableValues dictionary) whenever a variable is encountered or return nil if it encounters a variable with no corresponding value.

… which actually means just return the dictionary entry from the variable values:

    private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
                ...
            case .Variable(let symbol):
                return (variableValues[symbol], remainingOps)
            ...
    }


The test case from the previous task will still work – because having set no variable the return value will be nil. When the variable value is set and the variable is pushed again, this value will be returned. If you sum up those two variables, the return value should double:

class CalculatorTests: XCTestCase {
    
    func testPushOperandVariable() {
        var brain = CalculatorBrain()
        XCTAssertNil(brain.pushOperand("x"))
        XCTAssertEqual(brain.program[0] as String, "x")
        brain.variableValues = ["x": 3.14]
        XCTAssertEqual(3.14, brain.pushOperand("x")!)
        XCTAssertEqual(6.28, brain.performOperation("+")!)
    }
}

The complete code for the task #6 is available on GitHub.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.