5 Sequential programs

 

In this chapter you will learn

  • how to deal with lists of lists using flatten
  • how to write sequential programs using flatMap instead of for loops
  • how to write sequential programs in a readable way using for comprehensions
  • how to use conditions inside for comprehensions
  • how to get to know more types that have flatMap

Inside every large program is a small program struggling to get out.

—Tony Hoare, “Efficient Production of Large Programs”

Writing pipeline-based algorithms

One of the most popular patterns in modern programming languages is pipelining. We can write many computations as a sequence of operations—a pipeline—that together make a bigger, more involved operation. It’s a different take on creating sequential programs. *

* In this chapter we will talk about sequential algorithms or sequential programs. A sequential program is a piece of code representing logic that takes a value, transforms it in a step-by-step manner (sequentially), and returns a final value.

Let’s look at an example. We have a list of three interesting books:

case class Book(title: String, authors: List[String])

val books = List(
 Book("FP in Scala", List("Chiusano", "Bjarnason")),
 Book("The Hobbit", List("Tolkien")),
 Book("Modern Java in Action", List("Urma", "Fusco", "Mycroft"))
)

Our task is to count how many of them have the word “Scala” in the title. Having already met map and filter we can write the solution.

Composing larger programs from smaller pieces

Recommending book adaptations

The imperative approach

Problems with the imperative solution    

flatten and flatMap

Practical use case of using more flatMaps

Are we allowed to do this?