5 Sequential Programs

 

In this chapter you will learn how to

  • deal with lists of lists using flatten
  • write sequential programs using flatMap instead of for loops
  • write sequential programs in a readable way using for comprehensions
  • use conditions inside for comprehensions
  • 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"

5.1 Writing pipeline-based algorithms

One of the most popular pattern 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.

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

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

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:

05_29

5.2      Composing larger programs from smaller pieces

5.3      The imperative approach

5.4      flatten and flatMap

5.5      Practical use case of using more flatMaps

5.6      flatMap and changing the size of the list

5.7      Coffee Break: Dealing with lists of lists

5.8      Coffee Break Explained: Dealing with lists of lists

5.9      Chained flatMaps & maps

5.10  Nested flatMaps

5.11  Values that depend on other values

5.12  Practicing nested flatMaps

5.13  A better syntax for nested flatMaps

5.14  For comprehensions to the rescue!

5.15  Coffee Break: flatMaps vs for comprehensions

5.16  Coffee Break Explained: flatMaps vs for comprehensions

5.17  Getting to know for comprehensions

5.18  It’s not the for you are looking for!

5.19  Inside a for comprehension

5.20  More sophisticated for comprehensions