// // simple demo of using recursive functions to operate on arrays // (uses higher-order function) // println("type in list values (integers), quit to end") val list = fillList() println("you entered:") printList(list) // try several different ways of using listCombine println("sum is " + listCombine(list, sum, 0)) println("product is " + listCombine(list, product, 1)) println("sum is " + listCombine(list, (x,y) => x+y, 0)) println("product is " + listCombine(list, (x,y) => x*y, 1)) println("sum is " + listCombine(list, _ + _, 0)) println("product is " + listCombine(list, _ * _, 1)) // also try using it to compute min, max println("min is " + listCombine(list, (x,y) => (x min y), Int.MaxValue)) println("max is " + listCombine(list, (x,y) => (x max y), Int.MinValue)) def fillList() : List[Int] = { val input = readLine if (input == "quit") { List[Int]() } else { val num = input.toInt num :: fillList() } } def printList(ll : List[Int]) { if (!ll.isEmpty) { println(ll.head) printList(ll.tail) } } def sum(x : Int, y : Int) : Int = x + y def product(x : Int, y : Int) : Int = x * y def listCombine(list : List[Int], combine : (Int, Int) => Int, identity : Int) : Int = { if (list != Nil) { combine(list.head, listCombine(list.tail, combine, identity)) } else { identity } }