Limitations of Normal Functions

At the core of functional programming are functions or so-called higher-order functions. To get a feel for what these are, let’s start with a familiar function.

To find the sum of values in a given range 1 to number we’d probably write code like this:

 
def sum(number: Int) = {
 
var result = 0
 
for​(i <- 1 to number) {
 
result += i
 
}
 
result
 
}

That’s familiar code—we’ve all written code like this a million times over in different languages. That’s called imperative style—you tell not only what to do, but also how to do it. That’s dictating a low level of details. In Scala, you can write imperative code like this where it make sense, but you’re not restricted to that.

While this code got the work done, it’s not extensible. Now, if in addition, we need to count the number of even numbers and the number of odd numbers in the given range, that code will fall flat; we’d be tempted to use the infamous reuse by copy-paste-and-change pattern. Cringe! That’s the best we can do with normal functions, but that’d lead to code duplication with poor reuse.

Let’s take another shot at the simple problem on hand. Instead of the imperative style, we can program the same problem in functional style. We can pass an anonymous function to the function that iterates over the range. In other words, we make use of a level of indirection. The functions we pass can hold different logic to achieve different tasks over the iteration. Let’s rewrite the previous code in functional style.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.63.184