Functions Returning Functions
We know that in Scala, functions can return other function. In this lesson we will explore how that is.
A Recap
Let’s look at the summation functions which we created using anonymous functions.
def sumOfInts(a: Int, b: Int) = sum(x => x, a, b )def sumOfCubes(a: Int, b: Int) = sum(x => x*x*x, a, b)def sumOfFactorials(a: Int, b: Int) = sum(factorial, a, b)
Notice how a
and b
are being passed from the summation functions to the sum
function without any modifications, completely unchanged.
Because Scala is all about concise code, we will rewrite our summation functions to remove any unnecessary parameters.
First, we will have to rewrite the sum
function. Just to jog up the memory, here is the current sum
function.
Scala
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}// Driver Codedef sumOfInts(a: Int, b: Int) = sum(x => x, a, b )println(sumOfInts(1,5))
...