Monday, September 12, 2011

Scala By Example Chapter 5 Solutions - Exercise 5.2.2

Exercise5.2.2 Write a function product that computes the product of the values of functions at points over a given range.

This is very similar to the sum function that is already worked out in the chapter.

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

No comments: