// // simple demo of using lists with recursive functions // // print elements of list, one per line def printList(l : List[Int]) { if (!l.isEmpty) { println(l.head) printList(l.tail) } } // get list of elements read from standard input until "quit" def inputList() : List[Int] = { println("next value?") val input = readLine if (input == "quit") { Nil } else { input.toInt :: inputList() } } // get sum of elements of list def sumList(l : List[Int]) : Int = { if (!l.isEmpty) { l.head + sumList(l.tail) } else { 0 } } // get "reduction" of elements of list // combines elements pairwise using "combine" function, returning // identityElement at end of array def combineList(l : List[Int], combine : (Int,Int) => Int, identityElement : Int) : Int = { if (!l.isEmpty) { combine(l.head, combineList(l.tail, combine, identityElement)) } 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("enter elements for list, 'quit' to end") val nums = inputList() printList(nums) println("sum " + sumList(nums)) println("sum another way: " + combineList(nums, add, 0)) println("sum yet another way: " + combineList(nums, (x,y) => x+y, 0)) println("sum yet one more way: " + combineList(nums, _+_, 0)) println("product: " + combineList(nums, multiply, 1)) println("minimum: " + combineList(nums, smaller, Int.MaxValue)) println("maximum: " + combineList(nums, larger, Int.MinValue))