High-Order functions in Scala


I am posting the code snippet that progressively shows how the higher order functions can be written in Scala programming language

I will detail the steps a bit later, code for now.

class intSum {

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

def multiSum(addend: Int, a: Int, b: Int) : Int = {
if(a > b) 0;
else add(a,addend) + multiSum(addend, a+1,b)
}

def prodSum(prodend: Int, a: Int, b: Int) : Int = {
if(a > b) 0;
else multiply(a,prodend) + prodSum(prodend,a+1,b)
}

def add(base: Int, no: Int) : Int = {
base+no
}

def multiply(base: Int, multiplicand: Int) : Int = {
base * multiplicand
}

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

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

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

object intSumApp{
def main(args: Array[String]){
var is = new intSum()
println(” The value of multisum is ” +is.multiSum(1,1,5))
println(“The value of prodsum is “+is.prodSum(2,1,6))
println(” The value of multisum with func is ” +is.multiSumWithFunc(x=> x+1,1,5))
println(“The value of prodsum with func is “+is.prodsumWithFunc(x=>x*2,1,6))
println(” The value of multisum is ” +is.addWithFunc(x=>x+1) (1,5))
var addf = is.addWithFunc(x=>x+1) _;
println(” The value of multisum is ” +addf(1,5))
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s