// // demo of some simple functions on arrays implemented with loops // import scala.io.StdIn._ // get array of doubles from stdin, prompting for size first def readArray() : Array[Double] = { println("enter number of values") val sz = readInt val a = new Array[Double](sz) for (index <- 0 until sz) { println("next value?") a(index) = readDouble } a } // print array values def printArray(a:Array[Double]) { for (elem <- a) { println(elem) } } // reduction functions from array-demo rewritten to use loops // approach from class, based on array-demo-2 version /* def newSumArray(a:Array[Double]) : Double = { var sum = 0.0 for (elem <- a) { sum += elem } sum } */ // perform reduction on array elements // (returns "identity" if size of array is zero) def combineArray(a:Array[Double], combine:(Double,Double)=>Double, identity:Double ) : Double = { var result = identity for (elem <- a) { result = combine(result, elem) } result } // reduction functions from array-demo def newSumArray(a:Array[Double]) : Double = { combineArray(a, _ + _, 0.0) } def newProductArray(a:Array[Double]) : Double = { combineArray(a, (x1,x2) => x1*x2, 1.0) } def newMaxArray(a:Array[Double]) : Double = { combineArray(a, (x1,x2) => x1 max x2, Double.MinValue) } def newMinArray(a:Array[Double]) : Double = { combineArray(a, (x1,x2) => x1 min x2, Double.MaxValue) }