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.
Let’s revisit our summation program using the anonymous function. Before we get started, here is the code we have written so far.
Press + to interact
// 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.
Press + to interact
def sum(f: Int => Int, a: Int, b: Int): Int ={if(a>b) 0else f(a) + sum(f, a+1, b)}
The ...