// // demo of some simple functions on lists implemented with recursion // import scala.io.StdIn._ // get list of doubles from stdin, ending with "quit" def readList() : List[Double] = { println("enter next value, 'quit' to end") val in = readLine if (in == "quit") { List[Double]() } else { in.toDouble :: readList() } } // print elements of list def printList(a:List[Double]) { if (!a.isEmpty) { println(a.head) printList(a.tail) } } // sum elements of list // (returns zero for empty list) def sumList(a:List[Double]) : Double = { if (!a.isEmpty) { a.head + sumList(a.tail) } else { 0.0 } } // perform reduction on list // (returns "identity" for empty list) def combineList(a:List[Double], combine:(Double,Double)=>Double, identity:Double ) : Double = { if (!a.isEmpty) { combine(a.head, combineList(a.tail, combine, identity)) } else { identity } } // reduction functions analogous to those in array-demo def add(x1:Double,x2:Double) : Double = { x1+x2 } def newSumList(a:List[Double]) : Double = { // combineList(a, add, 0.0) // combineList(a, (x1,x2) => x1+x2, 0.0) 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) }