If the above code appears a bit intimidating, don’t worry. Let’s go over it step by step.
Line 1 is defining the function sum.
svg viewer
The dark green section of the illustration above represents the parameters of the function sum which is a single parameter that takes a function which further takes a single parameter of type Int and returns a value of type Int.
The red section of the illustration represents the return value of sum which is another function. sum returns a function which takes two parameters, both of type Int, and returns a value of type Int.
From line 2 onwards, we have the body of the function sum. This starts with a definition of a nested function sumHelper. sumHelper takes 2 parameters, a and b (the upper and lower bounds) and returns a value of type Int. The function body of sumHelper is identical to the function body of the previous sum function.
Line 5 is simply returning the sumHelper function.
In conclusion, sum is now a function that returns another function; particularly a locally defined or nested function.
Modifying the Summation Functions
Below shows how the summation functions would now be redefined. Notice how the parameters of the functions aren’t being specified anymore. This being said, when we call the functions, we still pass the upper and lower bounds as parameters.