// // demo of some simple functions on arrays implemented with recursion // import scala.io.StdIn._ // read values into array starting with firstIndex // (does nothing if firstIndex >= size) def readArray(firstIndex:Int, a:Array[Double]) { println("next value?") if (firstIndex < a.size) { a(firstIndex) = readInt readArray(firstIndex+1, a) } } // get array of doubles from stdin (prompting for size first) def readArray1() : Array[Double] = { println("enter number of values") val sz = readInt val a = new Array[Double](sz) readArray(0, a) a } // print array values starting with firstIndex // (does nothing if firstIndex >= size) def printArray(firstIndex:Int, a:Array[Double]) { if (firstIndex < a.size) { println(a(firstIndex)) printArray(firstIndex+1, a) } } // print array values def printArray1(a:Array[Double]) { printArray(0, a) } // compute sum of array elements starting at firstIndex // (returns 0 if firstIndex >= size) def sumArray(firstIndex:Int, a:Array[Double]) : Double = { if (firstIndex < a.size) { a(firstIndex) + sumArray(firstIndex+1, a) } else { 0.0 } } // compute sum of array elements def sumArray1(a:Array[Double]) : Double = { sumArray(0, a) } // perform reduction on array elements starting at firstIndex // (returns "identity" if firstIndex >= size) def combineArray(firstIndex:Int, a:Array[Double], combine:(Double,Double)=>Double, identity:Double ) : Double = { if (firstIndex < a.size) { combine(a(firstIndex), combineArray(firstIndex+1, a, combine, identity)) } else { identity } } // reduction functions as written in class def add(x1:Double,x2:Double) : Double = { x1+x2 } def newSumArray(a:Array[Double]) : Double = { // combineArray(0, a, add, 0.0) // combineArray(0, a, (x1,x2) => x1+x2, 0.0) combineArray(0, a, _ + _, 0.0) } def newProductArray(a:Array[Double]) : Double = { combineArray(0, a, (x1,x2) => x1*x2, 1.0) } def newMaxArray(a:Array[Double]) : Double = { combineArray(0, a, (x1,x2) => x1 max x2, Double.MinValue) } def newMinArray(a:Array[Double]) : Double = { combineArray(0, a, (x1,x2) => x1 min x2, Double.MaxValue) }