Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering Functional Programming

You're reading from   Mastering Functional Programming Functional techniques for sequential and parallel programming with Scala

Arrow left icon
Product type Paperback
Published in Aug 2018
Publisher Packt
ISBN-13 9781788620796
Length 380 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Anatolii Kmetiuk Anatolii Kmetiuk
Author Profile Icon Anatolii Kmetiuk
Anatolii Kmetiuk
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. The Declarative Programming Style FREE CHAPTER 2. Functions and Lambdas 3. Functional Data Structures 4. The Problem of Side Effects 5. Effect Types - Abstracting Away Side Effects 6. Effect Types in Practice 7. The Idea of the Type Classes 8. Basic Type Classes and Their Usage 9. Libraries for Pure Functional Programming 10. Patterns of Advanced Functional Programming 11. Introduction to the Actor Model 12. The Actor Model in Practice 13. Use Case - A Parallel Web Crawler 14. Introduction to Scala 15. Assessments 16. Other Books You May Enjoy

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.

Filtering

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>();
employees.add("Ann");
employees.add("John");
employees.add("Amos");
employees.add("Jack");
// 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);
System.out.println(result);

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(
"Ann"
, "John"
, "Amos"
, "Jack")
// Those employees with their names starting with 'A'
val result = employees.filter ( e => e(0) == 'A' )
println(result)

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.

You have been reading a chapter from
Mastering Functional Programming
Published in: Aug 2018
Publisher: Packt
ISBN-13: 9781788620796
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime