// // simple four-function calculator // // maintains a "current value" and repeatedly: // prompts for operation (+, -, *, /) and value // calculates and displayed new "current value" // // illustrates use of "match" and also using a function as a parameter to // another function // // the next line is needed to avoid warnings with the newest Scala // "comment it out" (insert a //) if you compile with an earlier version import scala.io.StdIn._ calcStep(0.0) // // perform one step: // prompt for operator and value // compute and display new value // def calcStep(current:Double) { println("\nenter one of +, -, *, /, q") val in = readChar in match { case '+' => { calculate(current, add) } case '-' => { calculate(current, sub) } case '*' => { calculate(current, mult) } case '/' => { calculate(current, div) } case 'q' => { println("done") } case _ => { println("invalid") ; calcStep(current) } } } // // perform the part of "calcStep" common to all four operators: // prompt for value, calculate and print new value // def calculate(current:Double, fcn:(Double,Double)=>Double ) { println("enter value") val in = readDouble val newValue = fcn(current, in) println("new value " + newValue) calcStep(newValue) } // // functions for four operators // def add(x:Double,y:Double) : Double = x + y def sub(x:Double,y:Double) : Double = x - y def mult(x:Double,y:Double) : Double = x * y def div(x:Double,y:Double) : Double = x / y