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

Curried Functions in Scala


The following sample code snippet shows the power of Scala Curried functions. Being a .Net developer, I am really amazed by having Scala support this with less code, in C#, we could achievesimilar to this with some Action arguments to the methods

Scala

Currying functions in Scala

Step1 : Define the lowest level of functionality

scala> def XTable(m: Int) (n: Int) = m*n
XTable: (m: Int)(n: Int)Int

Step2: Define a Semi-customized or partly specialized version of the above function

scala> def xTable2 = XTable(2) _
xTable2: Int => Int

Ste3: Consume the above function with values, to get the job done 🙂

scala> xTable2(5)
res11: Int = 10

Yet another Curried function
scala> def adder(m: Int, n: Int) = m + n
adder: (m: Int,n: Int)Int

scala> val curriedAdd = (adder _).curried
curriedAdd: Int => (Int => Int) = <function1>

scala> val addTwo = curriedAdd(2)
addTwo: Int => Int = <function1>

scala> addTwo(4)
res22: Int = 6