Higher-Order Functions in Scala
// Sum of all integers between a and b
def sumInts(a:Int, b:Int):Int =
if (a>b) 0
else a + subMints(a+1, b)
// Sum of cubes of all integers between a and b
def sumCubes(a:Int, b:Int):Int =
if (a>b) 0
else cube(a) + subCubes(a+1, b)
def cube(a: Int) =
x * x * x
// Sum of factiorials of all integers between a and b
def sumFactorials(a:Int, b:Int):Int =
if (a < b) 0
else sumFactorials(a) + sumFactorials(a+1, b)
Alternatively,
def sum(f:Int => Int, a:Int, b:Int):Int =
if (a > b) 0
else f(a) + sum(f, a + 1, b)
def sumInts(a:Int, b:Int) = sum(id, a, b)
def sumCubes(a:Int, b:Int) = sum(cube, a, b)
def sumFactorials(a:Int, b:Int) = sum(fact, a, b)
def id(x:Int):Int = x
def cube(x:Int):Int = x * x * x
def fact(x:Int):Int = if (x == 0) 1 else fact(x-1)
Function Type
Just like string type and integer type, Scala has something called function type. Function type A => B that takes an argument type A and returns a result of type B.
If we have, a:Int => b:Int, we categorize this as a function that map integers to integers.
Anonymous Function
Function without a name
def sumInts(a:Ints, b:Int) = sum(x => x, a, b)
def sumCubes(a:Ints, b:Int) = sum(x => x * x * x, a, b)
def sum(f: Int => Int, a: Int, b: Int): Int = {
def loop(a:Int, acc:Int): Int = {
if(a > b) acc
else loop(a+1, f(a)+acc)
}
loop(a,0)
}