Book Image

Scala Functional Programming Patterns

By : Atul S. Khot
Book Image

Scala Functional Programming Patterns

By: Atul S. Khot

Overview of this book

Scala is used to construct elegant class hierarchies for maximum code reuse and extensibility and to implement their behavior using higher-order functions. Its functional programming (FP) features are a boon to help you design “easy to reason about” systems to control the growing software complexities. Knowing how and where to apply the many Scala techniques is challenging. Looking at Scala best practices in the context of what you already know helps you grasp these concepts quickly, and helps you see where and why to use them. This book begins with the rationale behind patterns to help you understand where and why each pattern is applied. You will discover what tail recursion brings to your table and will get an understanding of how to create solutions without mutations. We then explain the concept of memorization and infinite sequences for on-demand computation. Further, the book takes you through Scala’s stackable traits and dependency injection, a popular technique to produce loosely-coupled software systems. You will also explore how to currying favors to your code and how to simplify it by de-construction via pattern matching. We also show you how to do pipeline transformations using higher order functions such as the pipes and filters pattern. Then we guide you through the increasing importance of concurrent programming and the pitfalls of traditional code concurrency. Lastly, the book takes a paradigm shift to show you the different techniques that functional programming brings to your plate. This book is an invaluable source to help you understand and perform functional programming and solve common programming problems using Scala’s programming patterns.
Table of Contents (19 chapters)
Scala Functional Programming Patterns
Credits
About the Author
Aknowledgement
About the Reviewers
www.PacktPub.com
Preface
Index

Concise expression


You always want to be able to concisely express yourself. Let's try the following command to create a string:

scala> val list = List("One", "two", "three", "Four", "five")
list: List[String] = List(One, two, three, Four, five)

We have created a list of strings. Note that we neither had to specify the type of the list for this, nor any new keyword. We just expressed that we wanted a list assigned to a read-only variable.

Code reviews do a lot of good to a code base. I keep looking for places where I can replace a variable assignment with variable initialization. Refer to the following URL for an example: http://www.refactoring.com/catalog/replaceAssignmentWithInitialization.html.

Scala helps us with the val keyword. With the use of this keyword, we can establish the following:

  • The initial value of variable must be specified (it is impossible for the variable to remain uninitialized).

  • The value of variable cannot ever be changed again (there is one less moving part).

Why is this so important? A system with less moving parts is easier to understand and explain. You will be knowing that Google is well known for its less-moving-parts software. Let's try the following command to check for the uppercase in these characters:

scala> def hasUpperCaseChar(s: String) = s.exists(_.isUpper)
hasLowerCaseChar: (s: String)Boolean

What does s.exists(_.isUpper) do? In this code, I have a string and I am checking whether it has one or more uppercase characters.

Note that I need to look at each character of the string to arrive at an answer as output. However, I did not have to split the string into its constituent characters and then work on each character.

I am just expressing the algorithm. The algorithm involves iterating all characters. However, I did not write a loop. Instead, I expressed what I meant, concisely. Scala's strings are collections of characters. We can try the following command to make use of a filter method:

scala> list filter (hasUpperCaseChar)
res2: List[String] = List(One, Four)

Just like a string, List is again a collection, in this case, of strings. I used a list method, filter, to weed out elements that did not satisfy the predicate.

If we were to write this imperatively, we would need a nested loop (a loop within another loop). The first loop would take each string, and the inner loop would work on each character of the string. We would need a list to collect the matching elements.

Instead of lists, we just declared what we wanted to happen. However, at some point of time in the code the looping needs to happen! It does happen indeed, but behind the scenes and in the filter method.

The filter method is a higher order function that receives the hasUpperCaseChar function.

Let's say, in addition to this method, we want only those string elements that have a length greater than 3:

scala> list filter (x => hasLowerCaseChar(x) && x.size > 3)
res1: List[String] = List(Four)

We are again executing the algorithm; however, with a different match criteria. We are passing a function in the form of a function literal. Each element in the list is bound to x, and we run a check on x.

The preceding form of expression allows us to concisely express our intent. A large part of this flexibility comes from the idea of sending small computations around that are expressible without much ado. Welcome to functions!