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.
①
books
.map(book => book.title)
.filter(title => title.contains("Scala"))
.size
① Remember that this is equivalent to

We have just created a pipeline! It consists of three _pipes_ , and each of them has an input and an output. We can connect them together only if the output of one of them has the same type as the input of the next one. For example, the `map` pipe outputs a `List[String]` . Therefore, we can connect it to any pipe that takes a `List[String]` as the input. This way, we connected three pipes together and formed a **pipeline, which is an encoding of the algorithm** that solves our original problem. It’s a step-by-step algorithm, or a sequential program, created using `map` and `filter` .
This is a very natural programming technique sometimes called chaining. If it feels natural to you already, you shouldn’t have any problems grasping this chapter’s content. If not, we will help you get there!
## Composing larger programs from smaller pieces
Pipelines can be constructed from smaller pieces of code that are composable and reusable. Hence, we can divide a larger problem into smaller parts, solve each of them individually, then create a pipeline to solve the original problem.
This approach is called divide and conquer, and it has been a Holy Grail for generations of programmers. Functional programmers try to use this approach whenever possible.
Recommending book adaptations 
Let’s see what our first objective is. Again, we have a list of books:
>
case class Book(title: String, authors: List[String]) val books = List(
Book("FP in Scala", List("Chiusano", "Bjarnason")),
Book("The Hobbit", List("Tolkien"))
)
We also have a function that returns a list of book adaptations ( `Movie` s) for any given author (for now, just Tolkien is supported):
>
case class Movie(title: String) def bookAdaptations(author: String): List[Movie] =
if (author == "Tolkien")
List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug"))
else List.empty
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if the author is `"Tolkien"` and no movies otherwise
**Our task is to return a feed of movie recommendations based on books.** The data shown above should result in a list of two feed items:
```
def recommendationFeed(books: List[Book]) = ??? ①
recommendationFeed(books)
→ List("You may like An Unexpected Journey,
because you liked Tolkien's The Hobbit",
"You may like The Desolation of Smaug,
because you liked Tolkien's The Hobbit")
```
① “ `???` ” in Scala means that an “implementation is missing.” It is used to leave some pieces out to be implemented later. This is part of the language. It compiles fine but fails at runtime.
The pseudocode that achieves the result above may look like
**Step 1** For each `book` → extract its authors.
**Step 2** For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
In the first part of this chapter, we will encode this algorithm as a purely functional pipeline—a sequential program.
## The imperative approach
**Step 1** For each `book` → extract its authors.
**Step 2** For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
The recommendation feed could be written as three nested `for` loops.
```
static List recommendationFeed(List books) {
List result = new ArrayList<>();
for (Book book : books)
for (String author : book.authors)
for (Movie movie : bookAdaptations(author)) {
result.add(String.format(
"You may like %s, because you liked %s's %s",
movie.title, author, book.title));
}
return result;
}
```
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if the author is `"Tolkien"` and no movies otherwise
If you’ve programmed in Java or any other modern imperative programming language, you should feel pretty confident about this code. It first creates a mutable list and then iterates over three collections in nested `for` loops. In the `for` loop’s body, new `String` elements are added to the mutable list. The last line returns this list as the result.
Problems with the imperative solution
There are three problems with the above solution.
 We need to use and return a mutable `Lis` `t`
Reads and updates of the `List` are spread across the whole function—in the first line, the last line, and inside the `for` body. It is harder to reason about such code. The bigger the function is, the worse this problem gets. We already discussed it in chapter 3.
 Each `for` adds another level of indentation
The more nesting there is in the code, the harder it is to read it. Nested loops with local variables are indented to the right, so adding more conditions usually means the programmer needs to scroll more.
 We use statements instead of expressions in the `for` body
The whole nested `for` returns nothing, so we need to add side-effecting statements inside the body to solve the original problem. That’s why we needed to use a mutable `List` . Additionally, usage of statements makes the code harder to test.
We will come back to the “expression vs. statement" problem later in this chapter.
## `flatten` and `flatMap`
**Step 1** For each `book` → extract its authors.
Step 2 For each `author` → call the `bookAdaptations` function, returning movies.
Step 3 For each `movie` → construct a recommendation feed string.
Let’s solve the problem using the functional paradigm, step by step. We start by extracting authors (Step 1 in the diagram above). Here’s our list of two books:
>
case class Book(title: String, authors: List[String]) ① val books = List(
Book("FP in Scala", List("Chiusano", "Bjarnason")),
Book("The Hobbit", List("Tolkien"))
)
① Note that a book can have more than one author.
`books`
a list of two books:
\- `Scala"` by Chiusano, Bjarnason
\- `Hobbit"` by Tolkien
Now, we want to get a list of all authors of those books:
Well, that’s not really what we wanted. Instead of the promised “list of all authors,” we got “list of lists of authors.” When we look closely at the function we passed to the `map` function, it becomes clear what happened: `book.authors` is a `List[String]` , so we mapped each element in the list to a new list, getting the list of lists. Mystery solved!
Fortunately, we can get rid of this unnecessary wrapping by using the `flatten` function, which, well, _flattens_ the list of lists into a list.
`flatten` goes through the list of lists and takes all elements from the first list, then second, and so on ...

The scenario of `map` ping using a function that returns an instance of the type we are mapping over—followed by a `flatten` —is so common that all functional languages provide a function that does both steps at once. In Scala, **this function is called `flatMap`** . Armed with this knowledge, we can now get a list of all authors with even less code:
>
books.flatMap(_.authors) // or: books.flatMap(book => book.authors)→ List("Chiusano", "Bjarnason", "Tolkien") ①
① See the difference between map and flatMap ?
## Practical use case of using more `flatMap` s
Step 1 For each `book` → extract its authors.
**Step 2** For each `author` → call the `bookAdaptations` function, returning movies.
Step 3 For each `movie` → construct a recommendation feed string.
We have built the first part of our pipeline and now have a list of authors at our disposal. In the second step we need to convert this list into a list of movies—some of their books’ adaptations. Fortunately, we have access to the `bookAdaptations` function we can use here.
>
val authors = List("Chiusano", "Bjarnason", "Tolkien") authors.map(bookAdaptations)
→ List(List.empty,
List.empty,
List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug")))
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if the author is `"Tolkien"` and no movies otherwise
We got list of lists again, but we now know exactly what to do:
>
authors.map(bookAdaptations).flatten
→ List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug"))
And if we connect both steps of our pipeline (starting with the list of `books` , not `authors` ), we will get
`books`
a list of two books:
`Scala"` by Chiusano, Bjarnason
`Hobbit"` by Tolkien

First `flatMap`
A given function is applied to both books, resulting in two lists, which are joined in sequence to produce a bigger list.
Second `flatMap`
A given function is applied to each element, producing three lists—two empty ones and one containing two movies. They are joined together to produce the final result.
## `flatMap` and changing the size of the list
Let’s see what really happened in the last example. We started out with two books, then
- the first `flatMap` returned a list of **three** authors and
- the second `flatMap` returned a list of **two** movies.

It is clear that `flatMap` not only can change the type of the list (e.g., from `Book` to `String` ) but also can change the **size** of the resulting list, which isn’t possible with `map` .
One question remains: where does a programmer make the decision about the size of the resulting list? To answer this question, let’s focus on the second `flatMap` from the last example. Let’s dissect it to separate calls of `map` and `flatten` :
>
val authors = List("Chiusano", "Bjarnason", "Tolkien") val movieLists = authors.map(bookAdaptations)
→ List(List.empty,
List.empty,
List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug"))))
We see here that using `map` on a list of three elements results in a new list of exactly three elements. However, the elements of this list are lists, so we need to `flatten` them to get a meaningful result. Again, `flatten` goes through each list and extracts elements to a new resulting list. And because two of the resulting three lists are empty, the resulting list holds only the elements from the third list. That’s why the third `flatMap` in the last example resulted in a list of two elements.
>
movieLists.flatten → List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug"))
Quick exercise: How many elements will there be? 
Tell how many elements the resulting lists will have:
```
List(1, 2, 3).flatMap(i => List(i, i + 10))
List(1, 2, 3).flatMap(i => List(i * 2))
List(1, 2, 3).flatMap(i =>
if(i % 2 == 0) List(i) else List.empty)
```
Answers:
6, 3, 1
## Coffee break: Dealing with lists of lists 
In this exercise we will work with the following `Book` definition:
>
case class Book(title: String, authors: List[String])
Here’s a function that takes a name of a friend and returns a list of their book recommendations:
>
def recommendedBooks(friend: String): List[Book] = { val scala = List(
Book("FP in Scala", List("Chiusano", "Bjarnason")),
Book("Get Programming with Scala", List("Sfregola")))
val fiction = List(
Book("Harry Potter", List("Rowling")),
Book("The Lord of the Rings", List("Tolkien")))
if(friend == "Alice") scala
else if(friend == "Bob") fiction
else List.empty
}
`recommendedBooks`
gets a friend name and returns a list of books they recommend:
\- Alice recommends `"FP in Scala"` and `"Get Programming in Scala"` .
\- Bob recommends `"Harry Potter"` and `"The Lord of the Rings"` .
\- Other friends don’t recommend anything.
Assuming we have a list of friends, compute the list of all books they recommend (replace ??? with the actual code).
val friends = List("Alice", "Bob", "Charlie") val recommendations = ???→ List(Book(FP in Scala, List(Chiusano, Bjarnason)),
Book(Get Programming with Scala, List(Sfregola)),
Book(Harry Potter, List(Rowling)),
Book(The Lord of the Rings, List(Tolkien)))
1
Having the list of all books recommended by our friends (created above), compute a list of authors they recommend .
val authors = ???→ List(Chiusano, Bjarnason, Sfregola, Rowling, Tolkien)
2
Try to solve the second exercise using just one expression—starting with the friends list—by chaining functions together.
3
Quick reminder about function signatures in `List[A]:`
- `def map(f: A => B): List[B]`
- `def flatten: List[B]` `// A` `needs to be a List`
- `def flatMap(f: A => List[B]): List[B]`
## Coffee break explained: Dealing with lists of lists 
We first look at functions and data at our disposal:
friends: List[String]
recommendedBooks: String => List[Book]
1
We have a `List[String]` and a function that takes a `String` and returns `List[Book]` . Our first idea is to use `map` .
>
val friends = List("Alice", "Bob", "Charlie") val friendsBooks = friends.map(recommendedBooks)
List(
List(
Book("FP in Scala", List("Chiusano", "Bjarnason")),
Book("Get Programming with Scala",List("Sfregola"))
),
List(
Book("Harry Potter", List("Rowling")),
Book("The Lord of the Rings", List("Tolkien"))
),
List()
)
`recommendedBooks`
gets a friend name and returns a list of books they recommend:
\- Alice recommends `"FP in Scala"` and `"Get Programming in Scala"` .
\- Bob recommends `"Harry Potter"` and `"The Lord of the Rings""` .
\- Other friends don’t recommendanything.
Oh, the dreaded list of lists! Fortunately, we know how to deal with it:
>
val recommendations = friendsBooks.flatten List(Book(FP in Scala, List(Chiusano, Bjarnason)),
Book(Get Programming with Scala, List(Sfregola)),
Book(Harry Potter, List(Rowling)),
Book(The Lord of the Rings, List(Tolkien)))
We solved the exercise using a `map` followed by a `flatten` . This combination reminds us that there is a shortcut called `flatMap` , which gives us the same result:
```
friends.flatMap(recommendedBooks)
```
For the second exercise, we already have a list of recommended books, so we need to just flatMap it with the _.authors function:
2
>
val authors = recommendations.flatMap(_.authors) List(Chiusano, Bjarnason, Sfregola, Rowling, Tolkien)
We can write it in just one expression by chaining the flatMap s:
3
```
friends
.flatMap(recommendedBooks)
.flatMap(_.authors)
```
## Chained `flatMap` s and `maps`
Step 1 For each `book` → extract its authors.
Step 2 For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
Let’s go back to our running example. We are able to get movies. Now, we need to construct the final step of the pipeline: the generation of recommendation feed strings. Currently, our pipeline looks like this:
>
val books = List( Book("FP in Scala", List("Chiusano", "Bjarnason")),
Book("The Hobbit", List("Tolkien")))
→ val movies = books
.flatMap(_.authors)
.flatMap(bookAdaptations)
→ List(Movie("An Unexpected Journey"),
Movie("The Desolation of Smaug"))
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if the author is `"Tolkien"` and no movies otherwise
For each movie, we need to construct a string in the form of
_“You may like_ `$movieTitle` _because you liked_ `$author’s $bookTitle.` ”
The solution seems to be very straightforward. We just need to `map` each movie and construct a string, right?
```
movies.map(movie => s"You may like ${movie.title}, " +
s"because you liked $author's ${book.title}") ①
```
① In Scala we can prefix any `String` literal with `s` to allow the compiler to interpolate values inside a given `String` . Only values wrapped in `${}` or prefixed with `$` are taken into account. For example, here `${movie.title}` will be changed to a given movie’s title during runtime. `$author` and `${book.title}` will also be replaced by their values. It’s similar to what we did in the Java version using `String.format` .
What’s the problem? We have access to neither author nor book inside the body of the mapping function! We can only create a string based on the `movie` , which only contains a `title` .
More formally, our `flatMap` s are **chained** one after another, and it means functions inside them have access only to a single element.

First, we go through the list of books and transform the list into a list of authors. Only then the next `flatMap` is called. The consequence is that we can only use simple one-parameter functions as transformations.
If we wanted to write a third `flatMap` and pass `book` to it, we would be unable to do so because they are in different scopes due to chaining.
## Nested `flatMap` s
Step 1 For each `book` → extract its authors.
Step 2 For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
What we really need to implement the third step of our pipeline is to have access to all intermediate values— `book` , `author` , and `movie` —in one place. Hence, we need to keep them all in the same scope.
To achieve this we can use **nested `flatMap`** s. Each pipeline step should be defined inside the existing scope, so each intermediate value is accessible in all steps.

This is how we can pass a multi-line function to `flatMap` , `map` , `filter` , or any other higher-order function.
Are we allowed to do this?
You may wonder whether the operation of switching from chained `flatMap` s to nested `flatMap` s is safe and warrants the same answer. Yes, it is safe. The answer will be exactly the same. Note that `flatMap` always returns a `List` , which, in turn, can be `flatMapped` . It doesn’t matter whether we use a chained version or a nested one—as long as we are using `flatMap` s, we stay in the context of a `List` .
**The `flatMap` function is very special.** We wouldn’t be able to transform chained `maps` into nested `maps` because `map` doesn’t guarantee that it returns a `List` , no matter what function we pass. `flatMap` does.
THIS IS BIG!
`flatMap` is the most important function in FP.
## Values that depend on other values
Step 1 For each `book` → extract its authors.
Step 2 For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
Now, let’s see nested `flatMap` s in action and finally solve the original problem! We will create a recommendations feed: all the movies produced by our pipeline will need to be transformed into a human-readable string.
 
In the left code snippet, we can only return a `String` created from the values produced by the previous `flatMap` (i.e., we only have the `movie` value in the scope). To solve this, we need additional access to `book` and `author` —our `String` value needs to depend on three values in the scope. We need to transform the chained code into a **nested `flatMap`** .
>
def recommendationFeed(books: List[Book]) = { books.flatMap(book =>
book.authors.flatMap(author =>
bookAdaptations(author).map(movie =>
s"You may like ${movie.title}, " +
s"because you liked $author's ${book.title}"
)
)
)
}
recommendationFeed(books)
→ List("You may like An Unexpected Journey,
because you liked Tolkien's The Hobbit",
"You may like The Desolation of Smaug,
because you liked Tolkien's The Hobbit"))
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if the author is `"Tolkien"` and no movies otherwise
`books`
a list of two books:
\- `"FP in Scala"` by Chiusano, Bjarnason
\- `"The Hobbit"` by Tolkien
This concludes the solution to the original problem. The `recommendationFeed` function is the functional programming version of the pipeline. It’s better than the imperative one but still has some of its problems. One may argue that the nesting is very similar to the nesting of imperative `for` loops, and I’d agree with that completely! Fortunately, there is a solution for this problem as well.
## Practicing nested `flatMaps` 
Before we move on, let’s make sure you are proficient with the nested `flatMap` s. Imagine you have defined the `Point` product type:
>
case class Point(x: Int, y: Int)
Fill out the blanks to produce a list specified below:
```
List( ??? ).flatMap(x => ①
List( ??? ).map(y => ①
Point(x, y)
)
)
→ List(Point(1,-2), Point(1,7))
```
① Again, read “ `???` ” as “missing implementation” in Scala. This code compiles fine but fails at runtime. It is used to leave some pieces out to be implemented later, especially when designing top-down. If they are part of an exercise, you need to replace them with real values to get a given answer.
As you can see, you need to fill two lists with numbers that would produce the desired resulting list. There are a few things worth remembering:
- We need to nest `flatMap` because we need access to both `x` and `y` to produce a single instance of `Point` .
- The last function is a `map` because the function we pass to it returns a `Point` value, not a `List` .
Answer
The only possible way to produce this list is this:
We wouldn’t be able to create such a list using chained `flatMap` and `map` because the `Point` constructor needs both values in its scope.
Bonus exercises 
Let’s play more with the example above. The original snippet generates two points. How many points would be generated by the code above if we
- Changed `List(-2, 7)` to `List(-2, 7, 10)` ?
- Changed `List(1)` to `List(1, 2)` ?
- Changed both of the above at once?
- Changed `List(1)` to `List.empty[Int]` ?
- Changed `List(-2, 7)` to `List.empty[Int]` ?
Answers:
3, 4, 6, 0, 0
## A better syntax for nested `flatMaps`
Our flatMap s became less readable when we started nesting them inside one another. We started nesting them because we wanted to have access to values from all chained lists, which is what we need in many pipeline-based sequential algorithms. Unfortunately, nesting makes code less readable, especially when we add more levels of indentation . *
*flatMap nesting and its readability are not just a Scala issue. We may have the same problem when we use map , flatMap , and other functions in other languages.
```
books.flatMap(book =>
book.authors.flatMap(author =>
bookAdaptations(author).map(movie =>
s"You may like ${movie.title}, " +
s"because you liked $author's ${book.title}"
)
)
)
```
So can we have our cake and eat it too? It turns out we can! Scala offers a special syntax that elegantly deals with nested `flatMap` s—the **for comprehension** . \* Let’s see it in action right away! Have a look at the section below, and don’t worry if you don’t understand what’s going on there. Focus on readability; we will dive into internals very soon.
\* **Other languages have this feature too** .
It’s worth noting that the for comprehension is not just a Scala-specific mechanism. For example, in Haskell we have a `do` notation that achieves the same goal.
Getting started with for comprehensions
We haven’t learned about for comprehensions yet, but before we do, let’s first see how they can help us.
A for comprehension looks like this:
```
for {
x <- xs
y <- ys
} yield doSomething(x, y) ①
```
① Note that this is not a `for` loop! This is a totally different mechanism, which has a similar name and uses the same keyword. We don’t use `for` loops in functional programming. We have a `map` for that!
It reads like English: for each element `x` in `xs` and for each element `y` in `ys` , call the function `doSomething(x, y)` . For example, if `xs` is a `List(1, 2)` and `ys` is a `List(3, 4)` , then the for comprehension will end up calling `doSomething` four times:
```
doSomething(1, 3), doSomething(1, 4),
doSomething(2, 3), doSomething(2, 4).
```
The Scala compiler **transforms the for comprehension** above into the more familiar nested code, which does exactly the same thing:
```
xs.flatMap(x => ys.map(y => doSomething(x, y)))
```
## For comprehensions to the rescue!
**Step 1** For each `book` → extract its authors.
**Step 2** For each `author` → call the `bookAdaptations` function, returning movies.
**Step 3** For each `movie` → construct a recommendation feed string.
Now that we know how to mechanically transform nested `flatMap` calls into nicer, more readable for comprehension syntax, let’s try to rewrite our original problematic example line by line to make it more readable.
```
for {
books.flatMap(book => ...
⤿ book <- books
book.authors.flatMap(author => ...
⤿ author <- book.authors
bookAdaptations(author).flatMap(movie => ...
⤿ movie <- bookAdaptations(author)
} yield s"You may like ${book.title}, " +
s"because you liked $author's ${book.title}"
```
Let’s see the for comprehension version of the solution in isolation.
>
for { book <- books
author <- book.authors
movie <- bookAdaptations(author)
} yield s"You may like ${movie.title}, " +
s"because you liked $author's ${book.title}"
→ List("You may like An Unexpected Journey,
because you liked Tolkien's The Hobbit",
"You may like The Desolation of Smaug,
because you liked Tolkien's The Hobbit"))
`books`
\- `"FP in Scala"` by Chiusano, Bjarnason
\- `"The Hobbit"` by Tolkien
`bookAdaptations`
a function that gets an author and returns a list of movies (adaptations of their books)
returns two movies if author is `"Tolkien"` , no movies otherwise
As you can see, the for comprehension version returns exactly the same answer as the imperative and nested `flatMap` solutions. But arguably, this code is far easier to read. Let’s read it in plain English:
- Extract each book from the books list.
- Then extract every author from each of the books above.
- Then, extract every movie from the book adaptations list (created by the `bookAdaptations` function) for each of the authors above.
- And for each such movie, produce a string value that is based on all the values extracted previously (i.e., `book` , `author` , and `movie)` .
## Coffee break: `flatMap` s vs. for comprehensions 
In this exercise we will work with the following definitions:
1
>
case class Point(x: Int, y: Int) val xs = List(1)
val ys = List(-2, 7)
Previously, we used nested flatMap s to produce a list of points:
## Coffee break explained: `flatMap` s vs. for comprehensions 
To solve the first exercise, we need to follow the mechanical transformation rules we defined earlier.
1

The code on the left can be transformed into the version on the right. We can follow the same technique with `ys` to get the final answer:
>
for { x <- xs
y <- ys
} yield Point(x, y)
→ List(Point(1, -2), Point(1, 7))
The second exercise is a bit harder, but we can still solve it using the mechanical transformation approach:
2
>
for { x <- xs
y <- ys
z <- zs
} yield Point3d(x, y, z)
→ List(Point3d(1, -2, 3), Point3d(1, -2, 4),
Point3d(1, 7, 3), Point3d(1, 7, 4))
As you can see, this looks very similar to the previous one. The additional list is just another line inside the for comprehension (no nesting!)
Now, let’s solve the third exercise to be able to compare the for comprehension above with the nested flatMap version. We need to follow the mechanical transformation but in the reverse order.
You can use both approaches (nesting or comprehensions), depending on what looks more readable and natural. In the remaining chapters we will be showing snippets of code that represent both styles.
## Getting to know for comprehensions
Now, let’s spend some time explaining inner workings of for comprehensions. We’ll start by discussing some historical background.
For comprehensions are used as a _syntactic sugar_ (i.e., they help write more comprehensible code, but they are not required to use). They are used as a replacement for three functions we have already met: `flatMap` , `map` , and `filter` .
THIS IS BIG!
You will find a lot of for comprehensions in functional programs.
In many languages this syntax is known as **list comprehensions** . Here is a sample of list comprehensions in a few languages for the expression equivalent to `list.filter(n => n < 10)` :
```sql
Python [n for n in list if n < 10] ①
CoffeeScript for n in list when n < 10 ①
Clojure (for [n list :when (< n 10)] n) ①
Haskell [n | n <- list, n < 10]
C# (predicates) list.Where(n => n < 10)
C# (queries) from n in list where n < 10 select n
SQL select n from list where n < 10
```
① Notice how some languages use the keyword `for` . This is a very different `for` than the one used to construct simple loops in imperative programming.
Q Why is it called a list comprehension?
A This may seem like a really strange name, but it is actually a very good choice in naming. Comprehension is the ability to understand something. So list comprehension is the ability to understand lists.
Q Why do we use the name “for comprehension" in Scala?
A In Scala the name is for comprehension because we can use it for various other types—not just lists. In fact, as we will see in the next chapters, functional programmers use them mainly in types other than `List` s. \*

\* And, again, as an example, Haskell also has its `do` notation that is used for the same purpose and works for more types than lists.
## It’s not the `for` you are looking for!
In Scala, a for comprehension is a first-class citizen of the language. Unfortunately for imperative programmers, it uses the keyword `for` .
Do not confuse the for expression in Scala with the traditional `for` statement in imperative programming. In imperative languages, we are accustomed to a `for` statement that simply loops over a collection using a counter or iterator.
In Scala, `for` is an **expression** . When used on a collection, it returns another collection with the transformed items. On the other hand, the imperative `for` is just a **statement** for constructing loops and returns nothing. That’s why imperative `for` loops (statements) can’t easily be used for immutable collections, which prefer expressions.
Statements vs. expressions 
There is an important distinction between a statement and an expression. A **statement** is a language construct that needs to change the state of a program to be useful. In imperative languages, some examples of statements are `for` , `while` , and even `if` . Here’s a Java snippet:
```
List xs = Arrays.asList(1, 2, 3, 4, 5);
List result = new ArrayList<>();
for (Integer x: xs) {
result.add(x * x);
}
```
An **expression,** on the other hand, doesn’t operate on the global state, always returns something, and, when executed many times, it always returns the same result. If you want your expression to be useful, you need to use its result in your program.
The above `for` statement can be transformed into a for expression in Scala (a for comprehension):
```
val xs = List(1, 2, 3, 4, 5)
val result = for {
x <- xs
} yield x * x
```
Remember! Functional programming is programming with expressions. Functional programmers don’t use statements.
Everything you successfully evaluate in your REPL is a valid expression. A value name is an expression, a function name is an expression, and a function call is an expression, too!
THIS IS BIG!
FP is programming with expressions, not statements.
## Inside a for comprehension
It’s time to finally define the generic shape of a for comprehension and how it translates into `flatMap` and `map` calls.
for { enumerators
} yield output-expression
Enumeratorsare the lines of code looking like this: x <- xs . It means that every value from xs is enumerated, extracted as x , and passed to the next enumerator or a yield expression . We can have as many enumerators as we want.
We don’t spend a lot of time on syntax in this book. However, the for comprehension is so prevalent and important that we needed to make an exception.
```
for {
a <- as ①
b <- bs ①
∙ ①
∙ ①
∙ ①
z <- zs ②
} yield function(a, b, ..., z) ③
```
① All but the last enumerators are translated into **`flatMaps`** .
② The last enumerator is transformed into a **`map`** .
③ The expression after `yield` degrnes the result of the whole `for` comprehension.

What’s the result type of a for comprehension?
If we can have many enumerators, what’s the algorithm the compiler uses to figure out the result type of the whole for comprehension? **The resulting container type is defined by the enumerator type, and the type of its elements is defined by the expression after `yield.` .**
>
for { a <- List[Int](1, 2) ①
b <- List[Int](10, 100)
c <- List[Double](0.5, 0.7)
d <- List[Int](3)
} yield (a * b * c + d).toString + "km"
→ List("8.0km", "10.0km", "53.0km", "73.0km", ②
"13.0km", "17.0km", "103.0km", "143.0km")
① The container type of the for expression is a List.
② Even though this comprehension goes through different lists (e.g., List[Int] and List[Double]), the whole expression yields a List[String].
In the code snippet above, the container type of the whole expression is `List` (all enumerators are based on `List` s). The type of its elements is the type of the expression after `yield` ( `String` here).
Not only lists are supported, though! We will come back to this topic later in the chapter.
## More sophisticated for comprehensions
Now, let’s use techniques we’ve learned so far in a brand-new pipeline. We will try to use for comprehensions and see how to model more sophisticated algorithms using them.
Is the point inside a given circle?
We are given a list of points and a list of radiuses:
>
case class Point(x: Int, y: Int)
val points = List(Point(5, 2), Point(1, 1))
val radiuses = List(2, 1)
**Our task is to figure out which points are inside circles with given radiuses and centers in `Point(0, 0)` .** The function that does it for one specific pair of point and radius is defined as follows:
Let’s look at the example below. Imagine we call the isInside function with radius = 1 and Point(1, 1) . In this case isInside returns false because Point(1, 1) is not inside a circle with radius 1 . On the other hand, the same Point(1, 1) is inside a circle with radius 2 . Thus, the isInside function returns true .
`isInside`
and returns a `Boolean`
returns `true` if the given point is inside the circle with the given radius

This problem can be modeled as a pipeline. What we need to do is call the `isInside` function for each possible pair of point and radius. The pseudocode may look like this:
**Step 1** Extract each possible `radius` .
**Step 2** Extract each possible `point` .
**Step 3** Call the `isInside(point, radius)` function, and return its result.
Yes! This is yet another **sequential program** ! Let’s use the techniques we have learned so far and write a for comprehension that quickly solves this problem.
## Checking all combinations using a for comprehension
**Step 1** Extract each possible `radius` .
**Step 2** Extract each possible `point` .
**Step 3** Call the `isInside(point, radius)` function, and return its result.
Again, here are lists of two points and two radiuses that we’ll work with:
>
val points = List(Point(5, 2), Point(1, 1)) val radiuses = List(2, 1)
We need to extract each radius as `r` , each point as `point` , and call the `isInside` function to get a result. We already know how to do that.
>
for { r <- radiuses
point <- points
} yield s"$point is within a radius of $r: " +
isInside(point, r).toString
→ List("Point(5,2) is within a radius of 2: false",
"Point(1,1) is within a radius of 2: true",
"Point(5,2) is within a radius of 1: false",
"Point(1,1) is within a radius of 1: false")
We were able to produce the result using a two-step for comprehension. As you can see, the solution is very concise and readable, but there is a small problem. We are returning a string with the description of the result for each point–radius combination. It seems that we could do better by returning a list of points that satisfy the condition. In the case above only Point(1,1) is within the given radius.
`isInside`
gets a point and a radius and returns a `Boolean`
returns `true` if the given point is inside the circle with the given radius
We were able to produce the result using a two-step for comprehension. As you can see, the solution is very concise and readable, but there is a small problem. We are returning a string with the description of the result for each point–radius combination. It seems that we could do better by returning a list of points that satisfy the condition. In the case above only `Point(1,1)` is within the given radius.
Filtering inside a for comprehension
We already know how to filter collections, and we can easily reuse this approach inside for comprehensions. Here’s how:
>
for { r <- radiuses
point <- points.filter(p => isInside(p, r))
} yield s"$point is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
There are two more approaches to perform filtering inside a for comprehension; one is mostly used with collections. The second one is more general and applicable beyond collection types, and it will serve as an introduction for more advanced usages of for comprehensions.
There are two more approaches to perform filtering inside a for comprehension; one is mostly used with collections. The second one is more general and applicable beyond collection types, and it will serve as an introduction for more advanced usages of for comprehensions.
## Filtering techniques
There are three basic techniques in Scala and functional programming that allow us to do filtering. We’ll compare them by solving the same problem and getting the same results. Here are the values we’ll use:
>
val points = List(Point(5, 2), Point(1, 1)) val radiuses = List(2, 1)
Using `filter`
We already solved the problem using the `filter` function from `List` .
>
for { r <- radiuses
point <- points.filter(p => isInside(p, r))
} yield s"$point is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
`isInside`
gets a point and a radius and returns a `Boolean`
returns `true` if the given point is inside the circle with the given radius
Using a guard expression ( `if` in a for comprehension)
Some FP languages have a special syntax that can be used to filter collections in for comprehensions. In Scala, the `if` keyword can be a separate step inside a for comprehension. In our case, to ensure that only `r` s and `point` s that satisfy the `isInside(r, point)` condition are `yield` ed, we can
>
for { r <- radiuses ①
point <- points
if isInside(point, r)
} yield s"$point is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
① We mention this approach briefly for the sake of completeness. We will be using the other two approaches in the rest of the book, as they are more universal.
Using a function passed to the `flatMap` function \*
We discussed how `flatMap` can change the size of a list, at the beginning of this chapter. Based on that, we can write a special function that we pass to `flatMap` (or in a for comprehension), which returns a list with one element if a condition is satisfied or an empty list otherwise.
\* Remember that `flatMap` s are generated from for comprehensions by the compiler.
>
def insideFilter(point: Point, r: Int): List[Point] = ① if(isInside(point, r)) List(point) else List.empty
for {
r <- radiuses
point <- points
inPoint <- insideFilter(point, r)
} yield s"$inPoint is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
① This approach is overkill for this particular problem. However, as we shall see, it is a more universal technique that can be used beyond collection types. Stay tuned!
## Coffee break: Filtering techniques 
In this exercise we will try to use filtering techniques to protect ourselves against invalid data. Imagine that the list of radiuses contains some mathematically invalid values:
>
val points = List(Point(5, 2), Point(1, 1)) val riskyRadiuses = List(-10, 0, 2)
What would happen if we ran our solution against those values? Let’s look at the `isInside` function and our current solution:
>
def isInside(point: Point, radius: Int): Boolean = { radius * radius >= point.x * point.x + point.y * point.y
}
for {
r <- riskyRadiuses
point <- points.filter(p => isInside(p, r))
} yield s"$point is within a radius of $r"
→ List("Point(5,2) is within a radius of -10","Point(1,1) is within a radius of -10",
"Point(1,1) is within a radius of 2")
The `isInside` function assumes that the radius we pass to it is nonnegative. If we pass negative values, it will return invalid results!
Let’s filter invalid radiuses
In this coffee break section, you will try to filter invalid radiuses (all that are nonpositive) before running the `isInside` function. You will use all three different filtering techniques we learned about in the last section.
Your first task is to write a for comprehension that solves the problem and filters only the valid radiuses using the filter function on List.
1
Your second task is to solve exactly the same problem using the guard expression ( if inside a for comprehension).
2
The third exercise is to solve the problem using a function passed to the flatMap function , using it as an enumerator in a for comprehension.
3
Note that the main reason for this coffee break is to get an intuition of how versatile flatMap is. It turns out mapping and flattening have plenty of useful applications!
The first technique we need to use should be very familiar. We can use the filter function on riskyRadiuses to filter only nonnegative values.
1
>
for { r <- riskyRadiuses.filter(r => r > 0)
point <- points.filter(p => isInside(p, r))
} yield s"$point is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
The second exercise should be solved by adding an if guard expression inside the for comprehension.
2
>
for { r <- riskyRadiuses
if r > 0
point <- points
if isInside(point, r)
} yield s"$point is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
The third exercise is the hardest one. We need to write another function, validateRadius , that takes a radius and returns it as a one-element List if it’s valid or an empty List if it’s not. This trick allows us to use it in flatMap or as another enumerator inside our for comprehension.
3
>
def insideFilter(point: Point, radius: Int): List[Point] = if (isInside(point, radius)) List(point) else List.empty
def validateRadius(radius: Int): List[Int] =
if (radius > 0) List(radius) else List.empty
for {
r <- riskyRadiuses
validRadius <- validateRadius(r)
point <- points
inPoint <- insideFilter(point, validRadius)
} yield s"$inPoint is within a radius of $r"
→ List("Point(1,1) is within a radius of 2")
As a bonus exercise, you can transform this for comprehension to raw `flatMap` / `map` calls. The answer can be found in the book’s code repository.
THIS IS BIG!
In FP, we build big programs from small functions.
You may feel that the last solution is a bit overcomplicated, but it has its benefits. **All the core logic is defined inside small functions, which are used to build a bigger algorithm inside the for comprehension** .
## Looking for a greater abstraction
So far we have learned how to deal with immutable values and collections, especially lists. We learned how to `map` things inside lists and how to `filter` them. In this chapter we’ve learned how to `flatMap` lists and how that helps us create pipeline-based algorithms. We focused on **creating small, reusable functions of our own** —and `map` , `filter` , and `flatMap` played a big role when we tried to connect them to build something bigger.
One may wonder, why are we so into lists? Is this really the most important thing in functional programming? Well, yes and no. Many things in programming can be modeled as lists. However, it’s not the main reason we use lists here. It turns out that lists encompass many techniques of functional programming—and these techniques are used pretty much everywhere in functional codebases. Therefore, understanding lists is a stepping stone to understanding greater abstractions. We are learning an abstraction by following concrete examples, which usually are lists. When we learn how something works with lists, we can then move on and try to use it with something different. This is **abstraction** at work.
THIS IS BIG!
FP heavily relies on abstracting common features—you learn once and use them everywhere.
Let’s see how this works when we try to learn `map` . Below are concrete examples of using `map` inside different types in Scala and Java:
Both snippets return a new list with all integers doubled.
Based on those two concrete examples, we can have a pretty good idea of how `map` would work for different types **in any language** . For example, what would the result of mapping over a tree be?
 \*
\* We are using an imaginary language that mixes text and graphics to show that it’s possible to build an intuition for an abstraction based on concrete examples.
We expect that all the values in the tree will be changed using the function we provide—and that **the shape of the tree data structure will be preserved** . And this is exactly the abstraction behind `map` !
## Comparing `map` , `foldLeft` , and `flatMap`
Before we move on to discuss more usages of the `flatMap` function in more types, let’s use `List` one more time to compare the practicalities behind the three important functions: `map` , `foldLeft` , and `flatMap` .
`List[A].map(f: A => B): List[B]`
Applies the function passed as **`f`** to each element of the original list, producing a new list with modified elements. The shape of the data structure ( **`List`** ), its size, and its sequence of elements are preserved.

When we write “shape of the data structure," we mean the internal structure of elements (e.g., a list shape is different than a tree shape).
`List[A].foldLeft(z: B)(f: (B, A) => B): B`
Accumulates a value of type **`B`** by applying the function passed as **`f`** to each element ( **`A`** ) of the original list and the current accumulator value ( **`B`** ). The shape of the data structure ( **`List`** ) is lost as well as its size and sequence of elements. Only one value of type **`B`** is returned.

However, in some cases `B` can be another `List` !
`List[A].flatMap(f: A => List[B]): List[B]`
Applies the function passed as **`f`** to each element of the original list—producing multiple lists (one for each element), which are joined in the same order as the elements they originated from. The shape of the data structure ( **`List`** ) is preserved, but the size may be different—it can be an empty list or a list multiple times bigger than the original one.

Remember how we used `flatMap` to filter out invalid values?
## Using for comprehensions with `Set` s
The last part of this chapter will be focused on learning the abstraction behind `flatMap` and for comprehensions, which we’ll use throughout the rest of the book. We have seen how to use them with lists. We need two more concrete examples to intuitively get the abstraction.
So, what are other types we can use for comprehensions with? Well, all the types that have flatMap function defined for them ! And believe me, there are lots of them in the functional programming ecosystem! We will learn about many of them soon, but let’s start with another collection type first: Set .
So, what are other types we can use for comprehensions with? Well, **all the types that have `flatMap` function defined for them** ! And believe me, there are lots of them in the functional programming ecosystem! We will learn about many of them soon, but let’s start with another collection type first: `Set` .
Using `Set` inside a for comprehension
There aren’t many differences between `List` and `Set` as far as their usage inside for comprehensions is concerned. Have a look:
As you see, in terms of mechanics, we are doing exactly the same thing. The choice of collection type, however, has a major impact on the values our for comprehension may return. Remember, `Set` s contain only unique values in an unspecified order, while `Lis` `t` s store all values in the order they were appended. We can see this difference in the example below:
>
for { a <- List(1, 2)
b <- List(2, 1)
} yield a * b
→ List(2, 1, 4, 2)
>
for {
a <- Set(1, 2)
b <- Set(2, 1)
} yield a * b
→ Set(2, 1, 4)
In both cases there were four multiplication operations. Each result was added to the underlying collection, which means we had four additions. However, the collection itself defined how those additions were processed. Hence, the `List` stored four elements. In case of `Set` , two of those four elements had the same value (there are two `2` s), so only three of them were stored.
## Using for comprehensions with many types
One question still remains. Can we use more than one type inside a for comprehension? More concretely, can we use `List` s and `Set` s in a single for comprehension? If so, what’s the collection type returned from interpreting the whole for comprehension? Let’s answer these questions by expanding on the previous example:
>
for { a <- List(1, 2)
b <- Set(2, 1)
} yield a * b
→ List(2, 1, 4, 2)
In this for comprehension we mixed `List` and `Set` but got `List` as a return type! So we now know that mixing is possible, but we don’t quite get why `List` was chosen over `Set` . Let’s figure it out by swapping the order of `List` and `Set` :
>
for { a <- Set(1, 2)
b <- List(2, 1)
} yield a * b
→ Set(2, 1, 4)
We are getting somewhere here! When we swapped the order and started with `Set` , the return collection was also a `Set` . When we started with `List` , the return collection was also a `List` . That’s how it works.
We can mix enumerator types
Provided that the compiler can cast the collection type of enumerators inside the for comprehension, we can easily mix them inside one for comprehension. The Scala compiler can cast a `List` into a `Set` , and it can cast a `Set` into a `List` , so mixing those types inside for comprehensions is possible.
The first enumerator defines the return type
When we mix types inside a for comprehension, the collection type of the first enumerator is the type that will be returned by the for comprehension expression. So if we start with `List` , all the following enumerators need to be cast to `List` s. If we start with `Set` , all the following enumerators will be cast to `Set` s. If it can’t be done, the compiler will complain.
## Practicing for comprehensions 
It’s time to make sure we are on the same page as far as for comprehension syntax is concerned. Please fill in the missing parts `(???)` of the code.
for { x <- List(1, 2, 3)
y <- Set(1)
} yield x * y
→ List( ??? )
1
for {
x <- ???
y <- List(1)
} yield x * y
→ Set(1, 2, 3)
2
for {
x <- ???(1, 2, 3)
y <- Set(1)
z <- Set( ??? )
} yield x * y * z
→ List(0, 0, 0)
3
Answers
- The first comprehension produces `List(1, 2, 3)` .
- The second comprehension returns a `Set` , so the first enumerator should be a `Set` .
>
for { x <- Set(1, 2, 3)
y <- List(1)
} yield x * y
Set(1, 2, 3)
- The third comprehension returns a `List` , so the first enumerator should be a `List` , and all the values are `0` , so the `yield` expression ( `x * y * z)` should always produce `0` . Since both `xs` and `ys` are defined as nonzero, we need to put zero in `zs` .
>
for { x <- List(1, 2, 3)
y <- Set(1)
z <- Set(0)
} yield x * y * z
List(0, 0, 0)
## Defining for comprehensions ... again
We already defined for comprehensions formally earlier in this chapter. However, we’ve learned two new things since then: **guard expressions** and **mixing types** . Let’s update the formal definition and include both of them inside the generic shape of the for comprehension.
```
for {
a <- as ①
b <- bs ①
∙ ①
∙ ①
∙ ①
z <- zs ②
} yield function(a, b, ..., z) ③
```
① All but the last enumerators are translated into **`flatMaps`** . Guard expressions are translated into **`filters`** .
② The last enumerator is transformed into a `map` .
③ The expression after `yield` defines the result of the whole `for` comprehension.
**An enumerator** can be one of two things: a generator or a guard expression ( `filter` ). We can have as many enumerators as we want.
**A generator** is the line of code looking like this: `x <- xs` . It means that _every value from `xs` is enumerated, extracted as `x` , and passed to the next `enumerator` or `yield` expression_ . Under the hood, it is transformed into a `flatMap` call or a `map` call if it’s a **last generator** inside `for` .
**A guard expression** is the line of code that looks like this: `if expression(x)` . It takes a value or values generated in previous steps and returns a `Boolean` value. Only the _values that satisfy the condition are passed to the next `enumerator` or `yield` expression_ . Under the hood, it is transformed into a `filter` call.
This is a simplistic explanation. Scala transforms guard expression into `withFilter` calls, which are lazy counterparts of `filter` . This is not an important distinction because we won’t use if guards in the book. Additionally, if you wonder what lazy means in this context, don’t worry, we will discuss this later in the book.
**A first enumerator** is a generator that defines the collection return type of the whole for comprehension. All the other generators must generate values in the collection that can be transformed into this type.
A **`yield` expression** defines the type of the objects inside the collection.
## Using for comprehensions with noncollection types
We’ve come a long way in learning about flatMap , pipelines, and sequential programs. We will use for comprehensions heavily in the rest of the book for many more types than List s and Set s. This chapter’s last example is also the first example of a for comprehension with a noncollection type.
This part of the chapter lays the foundation for the next chapter, where we’ll focus on error handling. Generally, the whole chapter is fundamental, because we’ll use for comprehensions and `flatMap` s in the remaining parts of the book. We’ll use them for handling collections, handling errors, doing some input and output, and even streaming!
Parsing historical events
Here’s a product type that stores some information about an event:
```
case class Event(name: String, start: Int, end: Int)
```
`Event` has a `name` , `start` year, and `end` year. Obviously, there are some rules that `Event` needs to follow:
- `name` should be a nonempty `String.`
- `end` year should be a reasonable number—say, less than 3,000.
- `start` should be less than or equal to `end` .
We want to write a function that will take a raw `name` , `start` , and `end` year and return a valid `Event` if it’s possible or an _empty_ value if not.
Ad hoc solution
Before we write a pipeline-based solution, let’s get the ad hoc, straightforward solution out of our systems and discuss its problems.

This solution works, but it’s not a perfect one in terms of separation of concerns. All the **concerns are entangled in one line of code** —the `if` line. The three requirements we defined above should be treated separately in our code. It’s not a big problem in this small example, but I’m sure you’ve seen and hated functions with lots of `if` clauses. Additionally, we’d like to **avoid using `null` s** . Let’s try to solve both problems!
## Avoiding `null` s: `Option` type
We will start by solving the problem of null s. Why do we want to avoid them in the first place? Well, there are several reasons, and we will discuss some of them in this book. Here we’ll just revisit one problem—a major one from a functional programming perspective. (More in chapter 6!)
`null` s make our signatures lie
The main problem is that `null` s make the signatures lie. Look at the solution proposed earlier:
Fun fact: Tony Hoare, the inventor of the null reference, called it his “one-billion dollar mistake."
```
def parse(name: String, start: Int, end: Int): Event
```
The signature says that the function returns an `Event` ... But it may, and does, also return a `null` ! This is a very serious trust issue. If we can’t say what the function does just by looking at its signature, we are no longer able to easily reason about our code. In functional programming, we want to build bigger programs from smaller ones, and to do that, **we need to have pure functions that don’t lie about the things they can potentially return** .
Enter the `Option` type
To deal with this problem, many languages introduced an `Option` type. **It models a value that may or may not be there** . It has two subtypes: `None` and `Some` . If the value is not present, `None` is returned. If it’s present, `Some` is returned with a concrete value inside.
 \*
\* Other languages refer to this type differently. Haskell calls it `Maybe` and Java calls it `Optional` . However, the idea is the same in all of them. Moreover, functional languages include some additional powers in these types (see the highlighted statement at the bottom of this page).
Armed with this type, we can rewrite our solution and make the signature of `parse` tell the truth and truth only:
```
def parse(name: String,
start: Int, end: Int): Option[Event] = {
if (name.size > 0 && end < 3000 & start <= end)
Some(Event(name, start, end))
else
None
}
```
It seems like a small change, but on top of a better signature, `Option` gives us something more: **it has a `flatMap` function** **!** Let’s use it!
## Parsing as a pipeline
The second problem with the ad hoc solution based on the `if` expression was that all three requirements were entangled together in one line of code. Let’s recall the requirements:
We will explore error handling and parsing in more depth in the next chapter. Treat this section as a small introduction to what’s possible.
```
case class Event(name: String, start: Int, end: Int)
```
- `name` should be a nonempty `String` .
- `end` year should be a reasonable number—say, less than 3,000.
- `start` should be less than or equal to `end` .
Ideally, we should be able to model each of those requirements as a separate small function that can be maintained and changed individually without affecting others. Only then will we achieve true separation of concerns in our codebase.
Let’s try to encode the requirements above as separate functions.
```sql
def validateName(name: String): Option[String] =
if (name.size > 0) Some(name) else None
def validateEnd(end: Int): Option[Int] =
if (end < 3000) Some(end) else None
def validateStart(start: Int, end: Int): Option[Int] =
if (start <= end) Some(start) else None
```
Having these functions and knowing that `Option` has the `flatMap` function, we can now use them to easily filter out invalid data using plain, flat, `if` -less code that reads almost like English.
① No nulls !No big if clauses!Built from smaller functions that define real business logic!
②None is much better than null because it’s a value of type Option[Event] , and you can use it as such everywhere, without any worries.
The pipeline has three steps, and **if any of them fails (i.e., returns `None` )** , the whole for comprehension returns `None` . This is exactly how we did it with lists; remember? We were able to filter out incorrect values by returning an empty `List` . **That’s the feature of `flatMap`** .
Recall the section where we discussed how `flatMap` can change the size of its output compared to the input. It works for `Option` too!
## Coffee break: Parsing with `Option` 
In this exercise we will do something that is very common in the software engineering world: we will add a new requirement. Our pipeline-based design will allow us to do this change very efficiently without touching the code responsible for other requirements.
The new requirements states
- The event needs to take more than 10 years to be valid.
Your first task is to write a function that takes start , end , and a minimal length ( minLength ) of the event and returns Some(length) only if it’s larger or equal to the minimal one. Here’s the signature:
Your second task is to use the function validateLength inside the for comprehension that we wrote earlier. It should be a part of a new function that parses raw data and returns an Option[Event] .
Note that we’ve used more imperative names for our pure functions in this chapter, like `parse` and `validate` . As we discussed earlier in the book, experienced functional programmers prefer more declarative names: `eventFromRawData` or `validEventName` .
Make sure you reuse the functions responsible for the three remaining requirements. You shouldn’t be concerned about their implementation, just their signatures.
```
def validateName(name: String): Option[String]
def validateEnd(end: Int): Option[Int]
def validateStart(start: Int, end: Int): Option[Int]
```
## Coffee break explained: Parsing with `Option` 
We can approach writing `validateLength` in the same way we approached the other three functions.
```sql
def validateName(name: String): Option[String] =
if (name.size > 0) Some(name) else None
def validateEnd(end: Int): Option[Int] =
if (end < 3000) Some(end) else None
def validateStart(start: Int, end: Int): Option[Int] =
if (start <= end) Some(start) else None
```
Based on the above, we just need an if expression, which returns Some if validation is successful and None otherwise.
Your second task is to use the function validateLength inside the for comprehension we wrote earlier. It should be a part of a new function that parses raw data and returns an Option[Event] .
2
```
def parseLongEvent(name: String,
start: Int, end: Int,
minLength: Int): Option[Event] =
for {
validName <- validateName(name)
validEnd <- validateEnd(end)
validStart <- validateStart(start, end)
validLength <- validateLength(start, end, minLength)
} yield Event(validName, validStart, validEnd)
```
Note how we used the fact that returning a `None` in one enumerator (a `flatMap` ) makes the whole expression `None` . We did the same when we specifically returned an empty `List` .
Note that we just needed to define a new function and add another step inside the for comprehension. We didn’t add anything to an existing `if` clause; we didn’t change any existing code at all. This is nice because no existing requirements have changed! This hopefully shows the power of real separation of concerns and of functions that can easily be composed together.
Treat this small section about Option as a teaser of what is coming next in chapter 6. We will need to add some error handling to our sequential programs. We’ll use flatMap , Option , and more!
## Summary
In this chapter you learned five very important skills that will be very useful in the remaining chapters and your own programming encounters.
CODE: `CH05_*`
Explore this chapter’s source code by looking at `ch05_*` files in the book’s repository.
Deal with lists of lists using `flatten`
We first encountered the problematic `List[List[String]]` when we tried to process books that had several authors. We learned that `List` s have the `flatten` function, which joins all the internal `List` s in order into one big list and returns it as a `List[String]` .
Write sequential programs using `flatMap` instead of `for` loops
Then, we introduced a function that is built on top of `flatten` and `map` : `flatMap` . It turned out that this function helps us build code that encodes functional pipeline-based algorithms—plain old sequential programs.
Write sequential programs in a readable way using for comprehensions
We still weren’t convinced about the readability of `flatMap` -based code. It still had high levels of indentation. We learned that this could be solved using a for comprehension, which is very popular in the functional programming world. In Scala, a for comprehension is transformed into nested `flatMap` / `map` calls by the compiler.
Use conditions inside for comprehensions
We learned that there are three ways of doing filtering inside a for comprehension: using the `filter` function, using a guard expression ( `if` inside a for comprehension), and using a function passed to the `flatMap` function. `filter` and guard expressions can only be used on specific types, like collections, while the last method is more generic and can be used on any type that has `flatMap` . We’ll use it in the following chapters.
Get to know more types that have `flatMap`
In the last part of the chapter, we became familiar with more types that have a `flatMap` function: `Set` and `Option` . We learned how to use multiple types inside a for comprehension and how to build a parsing functionality as a sequential pipeline using a for comprehension and `Option` type.