// // demo of some simple functions on lists implemented with loops // import scala.io.StdIn._ // get list of doubles from stdin, ending with "quit" def readList() : List[Double] = { // function to prompt for and read input -- put in function to avoid // duplication def getInput() : String = { println("enter next value, 'quit' to end") readLine } var tmp = List[Double]() var in = getInput() while (in != "quit") { // build list in reverse order since that's more efficient, then reverse // at end tmp = in.toDouble :: tmp in = getInput() } tmp.reverse } // print elements of list def printList(a:List[Double]) { for (elem <- a) { println(elem) } } // reduction functions from list-demo rewritten to use loops // perform reduction on array elements // (returns "identity" if size of array is zero) def combineList(a:List[Double], combine:(Double,Double)=>Double, identity:Double ) : Double = { var result = identity for (elem <- a) { result = combine(result, elem) } result } // reduction functions from list-demo def newSumList(a:List[Double]) : Double = { combineList(a, _ + _, 0.0) } def newProductList(a:List[Double]) : Double = { combineList(a, (x1,x2) => x1*x2, 1.0) } def newMaxList(a:List[Double]) : Double = { combineList(a, (x1,x2) => x1 max x2, Double.MinValue) } def newMinList(a:List[Double]) : Double = { combineList(a, (x1,x2) => x1 min x2, Double.MaxValue) }