Book Image

Mastering Functional Programming

Book Image

Mastering Functional Programming

Overview of this book

Functional programming is a paradigm specifically designed to deal with the complexity of software development in large projects. It helps developers to keep track of the interdependencies in the code base and changes in its state in runtime. Mastering Functional Programming provides detailed coverage of how to apply the right abstractions to reduce code complexity, so that it is easy to read and understand. Complete with explanations of essential concepts, practical examples, and self-assessment questions, the book begins by covering the basics such as what lambdas are and how to write declarative code with the help of functions. It then moves on to concepts such as pure functions and type classes, the problems they aim to solve, and how to use them in real-world scenarios. You’ll also explore some of the more advanced patterns in the world of functional programming such as monad transformers and Tagless Final. In the concluding chapters, you’ll be introduced to the actor model, which you can implement in modern functional languages, and delve into parallel programming. By the end of the book, you will be able to apply the concepts of functional programming and object-oriented programming (OOP)in order to build robust applications.
Table of Contents (17 chapters)

Declarative versus imperative collections

Another great illustration of how the declarative style works can be seen in collection frameworks. Let's compare the collection frameworks of an imperative and functional programming language, for example, Java (imperative) collections and Scala (functional) collections.

Why a collection framework? Collections are ubiquitous in any programming project. When you are dealing with a database-powered application, you are using collections. When you are writing a web crawler, you are using collections. In fact, when you are dealing with simple strings of text, you are using collections. Most modern programming languages provide you with the implementation of collection frameworks as part of their core library. That is because you will need them for almost any project.

We'll go into more depth about how imperative collections are different from declarative collections in the next chapter. However, for the purpose of an overview, let's briefly discuss one of the major differences between the imperative and declarative approaches to collections here. We can see such a difference using the example of filtering. Filtering is an ubiquitous operation that you most likely will find yourself doing pretty often, so let's see how it differs across the two approaches.


Java is a classic example of a very imperative approach to programming. And hence, in its collections, you will encounter operations that are typical of imperative programming. For example, consider that you have an array of strings. They are the names of the employees of your company. You want to create a separate collection with only those employees whose names start with the letter 'A'. How do you do that in Java?

// Source collection
List<String> employees = new ArrayList<String>();
// Those employees with their names starting with 'A'
List<String> result = new ArrayList<String>();
for (String e: employees)
if (e.charAt(0) == 'A') result.add(e);

First, you need to create a separate collection to store the result of your computation. So, we create a new ArrayList of strings. Afterward, you will need to check every employee's name to establish whether it starts with the letter 'A'. If it does, add this name to the newly created array.

What could possibly go wrong? The first issue is the very collection where you want to store your results. You need to call result.add() on the collection – but what if you have several collections, and you add to the wrong one? You have the freedom to add to any collection at that line of code, so it is conceivable that you add to the wrong one – not the dedicated one you have created solely for the purpose of filtering the employees.

Another thing that can go wrong here is that you can forget to write the if statement in the large loop. Of course, it is not very likely in such a trivial example, but remember that large projects can bloat and code bases can become large. In our example, the body of the loop has fewer than 10 lines. But what if you have a code base where the for loop is up to 50 lines, for example? It is not as obvious there that you won't forget to write your predicate, or to add the string to any collection at all.

The point here is that we have the same situation as in the loop versus go-to example. We have a pattern of an operation over a collection that might repeat itself in the code base. The pattern is something that is composed of more than one element, and it goes as follows. Firstly, we create a new collection to store the result of our computation. Secondly, we have the loop that iterates on every element of our collection. And finally, we have a predicate. If it is true, we save the current element into the result collection.

We can imagine the same logic executed in other contexts as well. For example, we can have a collection of numbers and want to take only those that are greater than 10. Or, we can have a list of all our website users and want to take the age of those users visiting the site over a particular year.

The particular pattern we were discussing is called the filter pattern. In Scala, every collection supports a method defined on it that abstracts away the filter pattern. This is done as follows:

// Source collection
val employees = List(
, "John"
, "Amos"
, "Jack")
// Those employees with their names starting with 'A'
val result = employees.filter ( e => e(0) == 'A' )

Notice that the operation remains the same. We need to create a new collection, then incorporate the elements from the old collection into the new collection based on some predicate. Yet, in the case of the pure Java solution, we need to perform three separate actions to get the desired result. However, in the case of the Scala declarative style, we only need to specify a single action: the name of the pattern. The pattern is implemented in the language internals, and we do not need to worry about how it is done. We have a precise specification of how it works and of what it does, and we can rely on it.

The advantage here is not only that the code becomes easier to read, and thus easier to reason about. It also increases reliability and runtime performance. The reason is that the filter pattern here is a member of the core Scala library. This means that it is well tested. It was used in a large number of other projects before. The subtle bugs that could have existed in such a situation were likely caught and fixed.

Also observe that the notion of anonymous lambdas gets introduced here. We pass one as an argument to the filter method. They are functions that are defined inline, without the usual tedious method syntax. Anonymous lambdas are a common feature of functional languages, as they increase your flexibility for abstracting logic.