// // simple demo of using arrays with recursive functions // // print elements of array, starting at startIndex, one per line def printArray(a : Array[Int], startIndex : Int) { if (startIndex < a.length) { println(a(startIndex)) printArray(a, startIndex+1) } } // get elements of array from standard input, starting at startIndex def inputArray(a : Array[Int], startIndex : Int) { if (startIndex < a.length) { println("next value?") a(startIndex) = readInt inputArray(a, startIndex+1) } } // get sum of elements of array, starting at startIndex def sumArray(a : Array[Int], startIndex : Int) : Int = { if (startIndex < a.length) { a(startIndex) + sumArray(a, startIndex+1) } else { 0 } } // get "reduction" of elements of array, starting at startIndex // combines elements pairwise using "combine" function, returning // identityElement at end of array def combineArray(a : Array[Int], combine : (Int,Int) => Int, identityElement : Int, startIndex : Int) : Int = { if (startIndex < a.length) { combine(a(startIndex), combineArray(a,combine,identityElement,startIndex+1)) } else { identityElement } } def add(x:Int, y:Int) : Int = { x + y } def multiply(x:Int, y:Int) : Int = { x * y } def smaller(x:Int, y:Int) : Int = { x min y } def larger(x:Int, y:Int) : Int = { x max y } println("how many elements?") val n = readInt val nums = new Array[Int](n) println("enter elements") inputArray(nums, 0) println("elements:") printArray(nums, 0) println("sum: " + sumArray(nums, 0)) println("sum another way: " + combineArray(nums, add, 0, 0)) println("sum yet another way: " + combineArray(nums, (x,y) => x+y, 0, 0)) println("sum yet one more way: " + combineArray(nums, _+_, 0, 0)) println("product: " + combineArray(nums, multiply, 1, 0)) println("minimum: " + combineArray(nums, smaller, Int.MaxValue, 0)) println("maximum: " + combineArray(nums, larger, Int.MinValue, 0))