These functions are all instances of {Summation from a to b} for different values of f . We can factor out the common pattern by defining a function sum

def sum(f: Int => Int, a: Int, b: Int): Int ={ if (a > b) 0 else f(a) + sum(f, a + 1, b) }

Using sum, we can formulate the three summing functions as follows.

def sumInts(a: Int, b: Int): Int ={ sum(id, a, b) }

def sumSquares(a: Int, b: Int): Int ={ sum(square, a, b) }

def sumPowerOfTwo(a: Int, b: Int): Int = { sum(powerOfTwo, a, b) }

where def id(x: Int): Int = x

def square(x: Int): Int = x * x

def powerOfTwo(x: Int): Int = { if (x == 0) 1 else 2 * powerOfTwo(x-1) }

Advertisements

Like this:

LikeLoading...

Related

This entry was posted on Monday, May 19th, 2008 at 4:06 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.