Summation with Anonymous Functions
In this lesson, we will see a practical example of anonymous functions and see how they allow you to write concise code.
We'll cover the following
Let’s revisit our summation program using the anonymous function. Before we get started, here is the code we have written so far.
// Higher-order sum functiondef sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}// Helper functiondef id(x: Int): Int = xdef cube(x: Int): Int = x*x*xdef factorial(x: Int): Int = if (x==0) 1 else x * factorial(x-1)// Summation Functionsdef sumOfInts(a: Int, b: Int) = sum(id, a, b)def sumofCubes(a: Int, b: Int) = sum(cube,a,b)def sumOfFactorials(a: Int, b:Int) = sum(factorial,a,b)
To write our summation functions using anonymous functions, we will start by creating our sum
function the same as before.
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}
The code for the sum
function hasn’t changed.
For this version of the program, we aren’t required to make helper functions and we can simply start defining our summation functions sumOfInts
, sumOfCubes
, and sumOfFactorials
. Where ever we inserted the helper functions in the previous program, we will now insert an anonymous function, i.e., the first argument of sum
.
sumOfInts
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}def sumOfInts(a: Int, b: Int) = sum(x => x, a, b )// Driver Codeprintln(sumOfInts(1,5))
sumOfCubes
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}def sumofCubes(a: Int, b:Int) = sum(x => x*x*x, a, b)// Driver Codeprintln(sumofCubes(1,5))
sumOfFactorials
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}def sumOfFactorials(a: Int, b:Int) = {sum({def f(x: Int):Int = if(x==0) 1 else x * f(x-1); f},a,b)}// Driver Codeprintln(sumOfFactorials(1,5))
As the helper function that was created for sumOfFactorials
was a recursive function, we needed to create an anonymous function by giving it a temporary name f
to allow the function to call itself in the function body.
This appears to make the code difficult to read. Hence, it is better to not call recursive functions anonymously.
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}def factorial(x: Int): Int ={if(x==0) 1else x * factorial(x-1)}def sumOfFactorials(a: Int, b: Int) = sum(factorial,a,b)println(sumOfFactorials(1,5))
In the next lesson, you will optimize a program using anonymous functions.