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.
To write our summation functions using anonymous functions, we will start by creating our sum function the same as before.
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
sumOfCubes
sumOfFactorials
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.
In the next lesson, you will optimize a program using anonymous functions.