Monday, September 12, 2011

Scala By Example Chapter 5 Solutions - Exercise 5.2.4

Exercise 5.2.4 Can you write an even more general function which generalizes both sum and product?

This function abstracts out the operation which can be passed in as a sum or product function. One thing to be noted here is that an extra argument needs to be passed as the base case which would be 0 for a sum and 1 for a product.

object OperatorOverRange {
def operateOverRange(f: Int => Int)(operate: (Int, Int) => Int)(base: Int)(a: Int, b:Int): Int =
if (a > b) base else operate(f(a), operateOverRange(f)(operate)(base)(a + 1, b))
def main(args: Array[String]) {
println("Sum of range of numbers from 3 to 8 is: " + operateOverRange(x => x)((x,y) => x + y)(0)(3,8))
println("Product of range of numbers from 3 to 8 is: " + operateOverRange(x => x)((x,y) => x * y)(1)(3,8))
}
}

No comments: