...

/

Summation with Anonymous Functions

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 function
def sum(f: Int => Int, a: Int, b: Int): Int ={
if(a>b) 0
else f(a) + sum(f, a+1, b)
}
// Helper function
def id(x: Int): Int = x
def cube(x: Int): Int = x*x*x
def factorial(x: Int): Int = if (x==0) 1 else x * factorial(x-1)
// Summation Functions
def 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) 0
else f(a) + sum(f, a+1, b)
}

The ...