// // simple demo of using recursive functions to operate on arrays // (uses higher-order function) // println("how many values?") val n = readInt val a = new Array[Int](n) fillArray(a, 0) println("you entered:") printArray(a, 0) // try several different ways of using arrayCombine println("sum is " + arrayCombine(a, 0, sum, 0)) println("product is " + arrayCombine(a, 0, product, 1)) println("sum is " + arrayCombine(a, 0, (x,y) => x+y, 0)) println("product is " + arrayCombine(a, 0, (x,y) => x*y, 1)) println("sum is " + arrayCombine(a, 0, _ + _, 0)) println("product is " + arrayCombine(a, 0, _ * _, 1)) // also try using it to compute min, max println("min is " + arrayCombine(a, 0, (x,y) => (x min y), Int.MaxValue)) println("max is " + arrayCombine(a, 0, (x,y) => (x max y), Int.MinValue)) def fillArray(aa : Array[Int], startIndex : Int) { if (startIndex < aa.size) { aa(startIndex) = readInt fillArray(aa, startIndex + 1) } } def printArray(aa : Array[Int], startIndex : Int) { if (startIndex < aa.size) { println(aa(startIndex)) printArray(aa, startIndex + 1) } } def sum(x : Int, y : Int) : Int = x + y def product(x : Int, y : Int) : Int = x * y def arrayCombine(aa : Array[Int], startIndex : Int, combine : (Int, Int) => Int, identity : Int) : Int = { if (startIndex < aa.size) { combine(aa(startIndex), arrayCombine(aa, startIndex + 1, combine, identity)) } else { identity } }