# flatmap

This is a page from my book, Functional Programming, Simplified

## Appendix: Scala `for` expression translation examples

Another Scala nested Option + flatMap example alvin August 8, 2017 - 1:35pm

After yesterday’s Scala nested Option + flatMap/for example, here’s another example of plowing through nested Options with `flatMap`. First, start with some nested options:

```val o1 = Option(1)
val oo1 = Option(o1)
val ooo1 = Option(oo1)
```

Here are those same three lines, with the data type for each instance shown in the comments:

This is a page from my book, Functional Programming, Simplified

## How to Enable the Use of Multiple Generators in a ‘for’ Expression

One cool thing about `for` expressions is that you can use multiple generators inside of them. This lets you do some nice analytics when you have some interesting data relationships.

For instance, suppose you have some data like this:

This is a page from my book, Functional Programming, Simplified

## How to Enable Filtering in a `for` Expression

Next, let’s see if we can use a filtering clause inside of a `for` expression with the `Sequence` code we have so far.

## Trying to use a filtering expression

When I paste the current `Sequence` class and this code into the Scala REPL:

``````val ints = Sequence(1,2,3,4,5)

val res = for {
i <- ints
if i > 2
} yield i*2``````

I see the following error message:

This is a page from my book, Functional Programming, Simplified

## How to Write a Scala Class That Can Be Used in a ‘for’ Expression

“You must unlearn what you have learned.”

Yoda, Star Wars

## Introduction

As a reminder, the reason for the next several lessons on `for` expressions is so that you can get to a point where you can understand the following code:

## Notes on Scala for expressions, map, flatMap, and Option

Without any explanation, these are some of my working notes from my upcoming book on Scala and Functional Programming about a) `for` expressions, b) `map`, c) `flatMap`, d) `Option`, and e) nested `flatMap` and `map` calls.

## These are equivalent (map and for)

this:

``val y = x.map(_ * 2)``

and this: