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:
