dgadiraju
5/9/2017 - 6:26 AM

func-anonymous.scala

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

//non recursive
def sum(f: Int => Int, a: Int, b: Int): Int = {
    var res = 0
    for(ele <- a to b by 1)
        res = res + f(ele)
    res
}

//anonymous functions defined as variables
val i = (i: Int) => i
val s = (i: Int) => math.pow(i, 2).toInt
val c = (i: Int) => math.pow(i, 3).toInt

sum(i, 1, 100)
sum(s, 1, 10)
sum(c, 1, 3)

//anonymous functions directly passed.
//This is very important and quite often used
sum((i: Int) => i, 1, 100)
sum((s: Int) => s * s, 1, 10)
sum((c: Int) => math.pow(c, 3).toInt, 1, 5)