In this chapter you will learn
-
how to use values to represent side-effectful programs
-
how to use data from unsafe sources
-
how to safely store data outside your program
-
how to indicate your code does have side effects
-
how to separate pure and impure code
“ … we have to keep it crisp, disentangled, and simple if we refuse to be crushed by the complexities of our own making … ”
—Edsger Dijkstra, “The Next Forty Years”
Talking to the outside world
In this chapter we’ll finally address the elephant in the room.
Q I now see how pure functions and trustworthy signatures can help me write better, more maintainable software. But let’s be honest. We will always need to get something from the outside—be it an API call or fetching things from a database. Additionally, almost every application in the world has a state that needs to be persisted somewhere. So isn’t this pure function concept a bit limited?
A We can talk with the outside and still use pure function goodies! The intuition here is exactly the same as with error handling (chapter 6) and modeling requirements as types (chapter 7). We represent everything as values of descriptive types!
Remember that if we write a function that may fail, we don’t throw exceptions. Instead, we indicate that it may fail by returning a value of a specific type (e.g., Either) . Analogically, when we want to have a function that takes only a specific combination of arguments, we indicate that in the signature by taking a specific type that models this assumption. We will show how you can apply exactly the same approach to generate and handle side effects! Remember that a side effect is anything that makes the function impure. Code that does IO actions is side-effectful and makes functions impure. Let’s see an example of this kind of function. The following code needs to persist a given meeting : void createMeeting(List<String> attendees, MeetingTime time) | IO and side effects We will use “IO" and “side effects" interchangeably in this chapter and the remaining pages of the book. It usually doesn’t matter what makes a function impure. What matters is that we need to handle it and assume the worst-case scenario, which is usually some kind of IO. |
As we discussed in chapter 2, such a function is not pure. More importantly, it lies in its signature by stating that it returns nothing ( void in Java). This technique is pretty popular in imperative languages. If a function doesn’t return anything, it probably does something underneath that’s important. To understand what it is—saving something in the database or just updating an internal ArrayList —a programmer needs to dive into an implementation. Pure functions don’t lie, which assures that reading code is a breeze because readers don’t need to go through each line of the implementation to understand what it’s doing on a higher level. We will show how to do these things in the spirit of functional programming by wrapping the createMeeting call in a pure function! | Pure function Returns a single value
Uses only its arguments
Doesn't mutate existing values
|
Integrating with an external API
Let’s backtrack a bit and introduce the requirements for this chapter’s application. Our task is to create a simple meeting scheduler.
Requirements: Meeting scheduler
-
For given two attendees and a meeting length, your function should be able to find a common free slot.
-
Your function should persist the meeting in the given slot in all attendees’ calendars.
-
Your function should use impure functions that talk with the outside world: calendarEntriesApiCall and createMeetingApiCall without modifying them. (Assume they are provided by an external client library.)
calendarEntriesApiCall and createMeetingApiCall functions do some IO actions. In this case these side-effectful IO actions are talking with some kind of calendar API . Let’s assume that these functions are provided by an external client library. It means we can’t change them but we are obliged to use them to implement the functionality properly because the calendar API holds the state of all people’s calendars.
Remember that by IO actions we mean actions that need to fetch data from or persist data outside of our program. These actions are often called side effects.
Calendar API calls
To make things simpler, we will not use a real API (yet!), but something that only simulates it, exposing a similar behavior—one that we could expect from a real-world API. We will use a MeetingTime product type as our data model. It is supported by simulated API calls that may not always succeed and may return different results each time they are called. This simulates accessing unknown data residing outside of our program.
We will introduce more problematic versions of “client library" functions soon. Plus, we will use a real API in chapters 11 and 12!
Properties of a side-effectful IO action
Our task is to create a meeting-scheduling function. It needs to be a pure function, too! That means it needs to have a signature that doesn’t lie. We also need it to use the two provided impure functions that are external to our code but do some crucial IO actions that our functionality will depend on: calendarEntriesApiCall and createMeetingApiCall . We wrapped them as impure Scala functions.
def calendarEntriesApiCall(name: String): List[MeetingTime]
def createMeetingApiCall(names: List[String],
meetingTime: MeetingTime): Unit ①
① The Unit type in Scala is equivalent to void in Java and other languages. If a function returns Unit , that means it does some impure things inside.
Again, we have to use both of them, and we can’t change them. Moreover, we may not even know how they are implemented inside (which is often the case when client libraries are provided as binaries). Also, we shouldn’t really care what’s inside them. The important bit is that they can’t be trusted. That’s the outside world for us. We should assume all the worst possible things about them! These functions may (and will) behave indeterministically.
We showed a simulated implementation that sometimes fails and returns random results for the sake of completeness. We won’t show it anymore and will focus on how FP handles such functions.
How IO actions may (mis)behave
In this chapter we will use an example of an API call, which represents an IO action. It’s a pragmatic approach, since everything may be represented as an API call (even a database call). Integrating with external APIs is a common programming activity, including pure FP codebases, so it’s important our logic is able to gracefully handle all the corner cases . We will handle all three scenarios in this book, but this chapter focuses mainly on the first two, which are exposed by the two “client library” *ApiCall functions we need to integrate with. These two impure functions that are provided as a part of the task return random results and throw random exceptions . They are written in Java as a convention but also to make sure we understand they are not part of our codebase. Remember that we can’t change them to make them more functional. But we’ll need to handle all their impurity in our pure functions! | Scala can use imperative code It’s worth noting that we can use Java functions in Scala, since they are both JVM languages. This is a pretty common scenario, since a lot of client libraries are written in Java, and they are imperative. You will be able to use all of them in your FP applications, including the big real-world app in chapter 11. |
Imperative solution to side-effecting IO code
Before we start introducing purely functional IO concepts, let’s set the stage and see how the meeting scheduler we are required to implement in this chapter would look like in imperative Java . We will use the provided API client library functions directly. Note that this solution includes many of the drawbacks we’ve already covered in previous chapters. We will address them all (as a recap), while refactoring this imperative, impure schedule function to a pure version, written in Scala.
I appreciate that modern Java is more functional, but I explicitly chose to use a more classical, imperative approach in our Java programs to compare these approaches. You will be able to apply many functional techniques from this book in your Java (and Kotlin!) programs as well.
Problems with the imperative approach to IO
There are many problems with the imperative solution even though it works correctly (kind of):
schedule("Alice", "Bob", 1) ①
→ MeetingTime[startHour=10, endHour=11]
schedule("Alice", "Bob", 2) ②
→ MeetingTime[startHour=12, endHour=14]
schedule("Alice", "Bob", 5) ③
→ null
schedule("Alice", "Charlie", 2)
→ MeetingTime[startHour=14, endHour=16]
① 1-hour meeting
② 2-hour meeting
③ 5-hour meeting can’t be scheduled.
calendarEntriesApiCall
calls a calendar API. Our simulated version:
- Returns two meetings for Alice: 8–10, 11–12
- Returns one meeting for Bob: 9–10,
- Returns one meeting for anyone else:
• Randomly starting between 8 and 12 and ending between 12 and 16.
• It may also fail (25% chance), so you need to be lucky (or persistent) to get these results.
However, as we’ve discussed many times in this book, code is read far more often than written , so we should always optimize for readability. This is the only way to ensure that the code is maintainable (i.e., it can be updated or changed by many future programmers with a highest-possible level of certainty). Here are the problems we can think of, based on what we know so far.
Note that an API call for “Charlie" may return different values each time it’s called (it’s impure) so you may get different results when you call schedule for “Charlie" (even null ).
Imperative solution Works for happy-path scenarios.
static MeetingTime schedule(String person1, String person2, int lengthHours)
Problem 1
The function has at least two responsibilities .
It calls external APIs, plus it sends a free slot, all done inside one function.
Problem 2
If any of the three external API calls fails, the whole function fails .
If there is any problem in the API call (network error, server error, etc.), the whole function fails with an exception, which may be confusing to the user. For now, our simulated API client library fails only sometimes, but that shouldn’t be a consolation, because it heavily aspects the imperative implementation of the schedule function we just wrote.We shouldn’t have assumed API calls would always succeed.
Problem 3
The signature lies .
The signature states that the function returns a MeetingTime, however, if an API call fails, it will throw an exception instead of returning a MeetingTime. Additionally, it will return null if no slot is available. (We already know how to model a thing that may not exist, and we will use this knowledge in the functional version of the schedule function. Do you remember what options are at our disposal?)
Can we really do better using FP?
Q Isn’t this a wild-goose chase? The majority of real-world applications will need to do IO, handle connection errors, and many more impure things. I don’t think we can do significantly better than the Java code you showed.
A Yes, we can do better. We don’t have to live with IO-based code spread all over our codebase. This would make our lives miserable. We will solve all three aforementioned problems by pushing the impurity out of most of our functions. This is the functional way.
THIS IS BIG!
In FP, we push the impurity out of most of our functions.
At the end of the chapter you will be able to write and understand the functional solution to the problem that looks like this:
def schedule(attendees: List[String],
lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(attendees)
possibleMeeting = possibleMeetings(scheduledMeetings,
8, 16, lengthHours).headOption
_ <- possibleMeeting match {
case Some(meeting) => createMeeting(attendees, meeting)
case None => IO.unit
}
} yield possibleMeeting
}
We are yet to cover how the IO type works, but note how rich the signature is and what it says about the function.
Additionally, note that this implementation is more versatile because it is able to schedule meetings for more than two people.
Our journey has already begun. We will address all three problems in this chapter by introducing functional programming alternatives and rewriting the schedule function to Scala, using these new concepts. Additionally, as promised, you will have a chance to recap the material from the previous chapters and see how all these functional pieces fall into place.
See how many familiar techniques are used in the snippet above!
Doing IO vs. using IO’s result
IO is an abbreviation for input/output. Hence, we have two types of IO.
The purpose of making this distinction is to help us think about IO from a different perspective. Some actions can be categorized as both input and output, which we’ll see later in the chapter.
Unsafe code
The main property of both types of IO actions is that they execute unsafe code, which is code that may behave differently, depending on many factors. That’s why reading from and writing to a shared mutable memory address is treated as unsafe and belongs to the side-effectful IO actions category. Remember that pure functions should always behave exactly the same, no matter where and when we use them.
Both actions are already represented in our API client library functions. calendarEntriesApiCall is an input action that reads a value from a potentially unsafe location, while createMeetingApiCall is an output action that writes a value to a potentially unsafe location.
Naturally, we’ll first focus on using IO to fetch data (i.e., input actions). Let’s dive into the beginning of the schedule function:
List<MeetingTime> person1Entries = calendarEntriesApiCall(person1); ①
List<MeetingTime> person2Entries = calendarEntriesApiCall(person2);
① Note we are still analyzing the imperative Java version we wrote a few pages ago.
The first line of the function is what you’d see in lots of codebases. It’s bad because it does two things:
-
Involves some IO action underneath (an API call, most likely over a network)
-
Provides the result of the IO action ( List<MeetingTime> )
Note that what really matters for us is the result, not the action itself . We want a List of MeetingTime values to be able to produce a potential slot for a meeting. But the fact that this value is fetched from the outside world has important consequences: it can fail (connection error), take too long, or simply have a different format than what we expect and fail with a deserialization error of some kind. To sum it up: we execute a reading IO action just to get a value, but we are drawn into some hairy corner cases in the process. And we need to handle them all!
In other words, reading IO actions focuses on the value they produce, while writing IO actions focuses on the side effect itself.
Handling IO imperatively
Even though we just care about a value produced by an IO action, we are forced to think about all the consequences of it being an IO action. Imperatively, in Java you’d need to do something like this:
Problem 1
The function has at least two responsibilities .
List<MeetingTime> person1Entries = null;
try {
person1Entries = calendarEntriesApiCall(person1);
} catch(Exception e) {
// retry:
person1Entries = calendarEntriesApiCall(person1);
}
Plus, similar code for person2Entries as well! This would probably be encapsulated in its own function/object, but it wouldn’t help with the problem we are trying to solve now.
Of course, it’s just a single possible solution to a much more complicated problem of detecting and dealing with failures. Basically, in such scenarios we try to have a recovery mechanism in case of a failure. Here we used a retry strategy with one retry. But there are many more options: more retries, using a cached value, using a default value (fallback), or retrying after some backoff period, to name a few. Recovery mechanisms are a huge topic, deserving their own book. What matters here is this: should we really care about a recovery strategy inside the schedule function . We should not! The more retries and try-catches, the less obvious the whole business logic is. The fact that we use IO in the schedule function should merely be a small detail because the most important thing is finding the free slot for a new meeting and storing it in the API. Did you see any mention of a retry strategy in the business requirements? | |
Entangled concerns
This mix of different responsibilities and levels of abstraction is called entangled concerns . The more concerns we entangle in one function, the more difficult the function will be to change, update, and maintain.
In Edsger Dijkstra’s words quoted at the beginning of this chapter: we will be “crushed by the complexities of our own making."
Note that we don’t say that the concern of retrying a potentially failing operation is not important. It is! What we say is that it can’t be entangled in the business logic code (i.e., it can’t distract the reader of the code from business concerns). Sure enough, if our schedule function consists of lots of try-catches or other failure-handling mechanisms, it can’t be very readable—and, therefore, not very maintainable.
Note that in the schedule function , we entangled the act of using a List<MeetingTime> with the fact that we needed an unsafe IO action to get it.
Let’s disentangle the fact of getting and using a value in our business-related code from the fact that we need a reading IO to fetch it.
Computations as IO values
Fortunately, functional programming has got our backs. Just like using the Either type to handle errors and the Option type to handle things that are possibly absent, we can use the IO type to disentangle the act of getting and using a value from an IO action that we need to execute to fetch that value. Let’s first see IO in action, and then we will dig deeper to build some intuition around it. That should be pretty easy because IO is very similar to Either , Option , and List — it even has many functions that you already know .
THIS IS BIG!
In FP, we just pass immutable values around!
First things first. IO[A] is a value, just like Option[A] is a value and Either[A, B] is a value. FP is all about functions and immutable values.
How does IO work?
IO[A] has several concrete subtypes, but we’ll introduce just two of them here for the sake of simplicity: Pure[A] and Delay[A] .
If we want to create a value of type IO[Int] , we need to decide whether it’s a value that we already know, or we need to run unsafe, side-effectful code to get it.
If we know the value, we can use an IO.pure constructor that will just wrap this value and return IO[A] (which, internally, is a Pure[A] ):
val existingInt: IO[Int] = IO.pure(6)
If we need to call an unsafe function getIntUnsafely() , which is an impure function that may throw exceptions, then we need to use the IO.delay constructor that will wrap the potentially unsafe call without executing it (using a mechanism similar to closures ).
val intFromUnsafePlace: IO[Int] =
IO.delay(getIntUnsafely())
No matter which constructor we choose ( pure or delay ), we get back an IO[Int] value. It’s a value that represents a potentially unsafe computation (like a side-effectful IO action) that, if successful, produces an Int value. Note the usage of the word represents in the previous statement. IO[Int] value is just a representation of a computation that will provide an Int value. We will need to somehow execute or interpret this IO[Int] to get the resulting Int value.
The functional IO type
in Scala is part of the cats-effect library. To use IO , you need to import cats.effect.IO first. You already have it in scope if you use the sbt console from the book’s repository.
The difference between IO.pure and IO.delay is that the former is an example of eager evaluation, while the latter is an example of lazy evaluation. We will discuss this in more depth later in the chapter.
What’s important now is that we use the power of lazy evaluation to not call unsafe code and delegate this responsibility to some other entity in a different place.
IO values
It’s very important to remember that IO[Int] , or IO[MeetingTime] , is just an immutable value like any other immutable value.
What is IO ?
IO[A] is a value that represents a potentially side-effectful IO action (or another unsafe operation) that, if successful, produces a value of type A .
Q So how exactly does IO help us? And what about the requirement that we need to use the impure calendarEntriesApiCall function, which is provided externally and potentially unsafe? Surely, we can’t change its signature because we can’t change it at all!
A We won’t change the calendarEntriesApiCall function. Usually, when you are provided with some external library that integrates with an outside-world system, you can’t easily change anything there. So calendarEntriesApiCall stays untouched! What we’ll do, however, is wrap this external, impure, side-effectful function within a function that returns an IO value!
In our example we have an unsafe function that acts as a client library function with the following unchangeable signature:
def calendarEntriesApiCall(name: String): List[MeetingTime] ①
① Compare both signatures. There is a fundamental difference, which we will dig into later on.
Since this is an IO action that we use to fetch a value, and we don’t want to be responsible for executing it; we can put it inside an IO[List[MeetingTime]] value using the IO.delay constructor:
> | import ch08_SchedulingMeetings.calendarEntriesApiCall
def calendarEntries(name: String): IO[List[MeetingTime]] = { ①
IO.delay(calendarEntriesApiCall(name))
}① Compare both signatures. There is a fundamental difference, which we will dig into later on. |
If you want to follow along in your REPL, please import the impure API client library functions from the ch08\_SchedulingMeetings module, as shown in the code snippet.
And that’s it! We used `calendarEntriesApiCall` as required. Our new function returns `IO[List[MeetingTime]]` , which is a pure value that represents an IO action, which, once successfully executed, will provide a `List[MeetingTime].` What’s cool about the `calendarEntries` function is that **it will never fail** , no matter how many exceptions `calendarEntriesApiCall` throws! So how exactly does it work, and what exactly have we achieved by doing so? Next, we’ll play with the `IO` type a bit, using a smaller example, so you get more intuition about it.
Values don’t throw exceptions, and pure functions don’t throw exceptions as well!
## `IO` values in the wild
`IO.delay` takes a block of code and doesn’t execute it, but it returns a value that _represents_ this passed block of code and the value it will produce when executed. Before we use (and execute) `IO` in our meeting scheduler, let’s see a smaller example first. Assume we have an impure Java function that prints a line and then returns a random number between 1 and 6.

Remember that we can use the Java code from Scala because they are both JVM languages. We are going to use this convention in the remaining part of the book. Java code represents imperative solutions, which usually are impure functions. In Scala, we will use them the FP way without any modifications. Hopefully, this approach aligns with your future experience.
After executing this function, we surprisingly get two results back.
> | import ch08_CastingDie.castTheDieImpure ① castTheDieImpure()
→ console output: The die is cast ②
→ 3 ① To follow along, import this function into an sbt console REPL session. ② What happened here? We call a function and get more than advertised in the signature? |
In fact, you get just one result—an `Int` , but the function itself prints an additional line, which we can treat as a side effect because it does more than advertised in the signature (which promises to just return an `Int` !). Additionally, when you run it the second time, there is a chance you will get a different result! It’s not a pure function, so as FP programmers, we need to treat it as a potential threat to code maintainability— **it’s an unsafe code that we need to wrap in an** `IO` !
Functional programmers treat all impure functions with the same level of scrutiny as IO actions.
Let’s wrap the impure function call inside an `IO` using `IO.delay` .
> | def castTheDie(): IO[Int] = IO.delay(castTheDieImpure()) → def castTheDie(): IO[Int]
castTheDie()
→ IO[Int] |
THIS IS BIG!
In FP, we treat impure functions as unsafe code.
And what? **Nothing happened!** `IO.delay` took a block of code (a call to `castTheDieImpure()` ) and didn’t execute it. It returned a value that _represented_ the passed block of code without executing it. No matter how many times we execute `castTheDie()` , it will always return the same `IO[Int]` value, just like `List(1, 2, 3)` will always return the same `List[Int]` value. No side effects are executed, no `printlns` , and no random numbers returned. `castTheDie()` returns a value that can later be interpreted ( _executed_ ) and may eventually provide an `Int` value by calling the `castTheDieImpure()` function lazily _stored_ inside. This allows us to **focus on using a generated `Int` value without running the code that generates it** . We will show how to _run_ and _use_ an `IO` next.
Problem 1
**The function has at least two responsibilities** .
In other words, the responsibility for running the unsafe code is delegated.
## Pushing the impurity out
We split the responsibilities of using a value produced by an IO action and running this IO action. Let’s first see how we run an `IO` value.
Running `IO` values
`IO[A]` can be run by executing a special function called **`unsafeRunSync`** **`()`** .
> | val dieCast: IO[Int] = castTheDie() → dieCast: IO[Int]
import cats.effect.unsafe.implicits.global ①
dieCast.unsafeRunSync()
→ console output: The die is cast
→ 3 ① We need to insert this import statement before running an IO value. It provides an access to thread pools, which will be used to execute delayed computations and side effects. We will discuss threads and concurrency in chapter 10. (BTW, the book’s sbt console session imports it automatically.) |
See? We can run it, and we get exactly the same behavior as running `castTheDieImpure()` previously (a printed line and a random `Int` value). However, in FP, we call `unsafeRunSync` in a different place, usually only once, at the end of our program, which only contains a small amount of impure code! A different entity is responsible for running it.
The main benefit of using `IO` is that it’s just a value, so it belongs to the pure world. We want to have as much code as possible in the pure world to use all the superpowers we’ve learned in this book to our advantage. All the impure functions—random generators, printing lines, API calls, and database fetches—belong to the impure world.
THIS IS BIG!
In FP, we push the impurity out of most of our functions.

Now, let’s see how we can work solely with `IO` values that represent side-effectful IO actions **without running them** ! `IO` values, just like `List` s, `Option` s, and `Either` s, can be transformed using pure functions. What’s more, these are the functions that you are already familiar with! Let’s feel the real power of the pure side of the world!
## Using values fetched from two IO actions
Enough theory ! It’s time to connect all the dots and use the power of functional programming to our advantage. We will first conclude the smaller _casting the die_ example and then we’ll ask you to implement a similar solution in the meeting scheduler!
Imagine that you’d like to cast the die twice and return a sum of both results. It looks trivial using the impure version:
> | castTheDieImpure() + castTheDieImpure() → console output: The die is cast
→ console output: The die is cast
→ 9 |
Easy, right? We get two printed lines and the final result of the function, which, in this case, was `9` . Now, remember that IO actions are usually connected to a higher risk of something not going according to the plan. We could say there is a chance that a die falls off the table.

Does `castTheDieImpure() + castTheDieImpure()` still look good in your opinion? If you didn’t know what’s inside the `castTheDieImpure` function and just relied on its signature, which promises to always return an `int` , you’d be in **big trouble** . Codebases in real projects are usually large, and you don’t have enough time to closely investigate each and every line of an implementation, do you?
Problem 1
**The function has at least two responsibilities** .
When a function returns an `Int` , its client can assume it will return an `Int` when called.
That’s where `IO` type comes in. We don’t want to think about try-catches in this particular place of our codebase, we just want to indicate the logic behind our program, which is _getting two numbers out of somewhere and summing them_ . Wouldn’t it be nice to say just this and get back a value that represents this and only this with no strings attached?
When a function returns an `IO[Int]` it indicates that it returns a value, which can later be executed, but it may contain some unsafe code and may fail. It will return an `Int` only if it succeeds.
> | def castTheDie(): IO[Int] = IO.delay(castTheDieImpure()) → def castTheDie(): IO[Int]
castTheDie() + castTheDie()
→ compilation error! ① ① This fails at compile time, because IO[Int] doesn’t define an addition operation. You can’t simply add two values that represent potentially unsafe computations! |
## Combining two `IO` values into a single `IO` value

Q We can’t simply add two `IO` values together? So how is it possible to combine them into one? Why does it need to be so hard?
```
castTheDie() + castTheDie()
→ compilation error!
```
A It can’t be added because an `IO[Int]` value represents more than just an `Int` value. It also represents a potentially side-effectful and unsafe action that needs to be executed later on because it may fail. Isn’t it helpful? As you see, it’s a pretty rich value, and we will use this fact to our advantage.
Let’s combine those `IO` s. Fortunately, we’ve already tackled a very similar problem: getting two numbers, and if they both exist, summing them.
> | val aOption: Option[Int] = Some(2) val bOption: Option[Int] = Some(4)
aOption + bOption
→ compilation error! |
This fails at compile time, because `Option[Int]` doesn’t define an addition operation. You can’t simply add two potentially absent values!
Do you remember what we used to combine two or more `Option` values? The answer is that we used our old friend, `flatMap` , which is used inside a for comprehension.
I hope it’s not a surprise for you, since we’ve been `flatMapping` and using for comprehensions since their introduction in chapter 5. `flatMap` is everywhere in functional programs.
> | val result: Option[Int] = for {
a <- aOption
b <- bOption
} yield a + b |
This whole for expression produces a value of type `Option[Int]` . In this case it’s `Some(6)` , but it would produce `None` if either `aOption` or `bOption` was `None` .
**It turns out** `IO` **has** `flatMap` **as well** .
> | def castTheDieTwice(): IO[Int] = { for {
firstCast <- castTheDie()
secondCast <- castTheDie()
} yield firstCast + secondCast
} |
This whole for expression produces a value of type `IO[Int]` . It describes a program to be executed in a different place.
We created a new function that returns an `IO[Int]` —a description of a program that, when executed later, will produce an `Int` , which will be a result of throwing the die twice. And since `IO` is just a pure value, there is no chance an exception is thrown here because we’ve not run it yet.
And since `castTheDieTwice` belongs to the pure world, we won’t run this value here. It will be delegated to the client of this function.
## Practicing creating and combining `IO` values 
The casting dies setup we have just described is very similar to a feature in the meeting scheduler app we’ve been working on in this chapter. We need to get calendar entries for two attendees and then _merge_ these two lists together to get a list of all scheduled meetings for both of them.
Given an impure side-effectful function that is potentially unsafe and returns a list of meetings for a given attendee: | 1 |
> | def calendarEntriesApiCall(name: String): List[MeetingTime] import ch08_SchedulingMeetings.calendarEntriesApiCall |
**write a pure `calendarEntries`** function that uses this function but returns only a value that describes what will happen once executed.
Remember to import both impure functions into your book’s `sbt console` REPL session.

Given an impure side-effectful function that is potentially unsafe and saves a given meeting for future use: | 2 |
> | def createMeetingApiCall(names: List[String], meetingTime: MeetingTime): Unit import ch08_SchedulingMeetings.createMeetingApiCall |
**write a pure function that uses this API call function** but returns only a value that describes what will happen once executed.

Your final task is to write a pure function that returns a description of a program that gets calendar entries for person1 and person2 and returns a single list of all their meetings. It should use calendarEntries inside (implemented above). Here’s the signature of this function: | 3 |
> | def scheduledMeetings(person1: String, person2: String): IO[List[MeetingTime]] |
Answer

## Disentangling concerns by working with values only
Problem 1
**The function has at least two responsibilities** .
We now have three functions that return an `IO` value. `calendarEntries` and `createMeeting` are simple wrappers around their impure counterparts (API calls). `scheduledMeetings` is a function that uses `calendarEntries` to return all meetings scheduled in the `person1` and `person2` calendars.
There is a small, but very important, distinction between imperative `calendarEntriesApiCall(String name)` and its functional _wrapper_ : `calendarEntries(name: String)` . The imperative one **does two things** :
- Returns a `List[MeetingTime]` for a given person
- Executes an IO action responsible for getting the `List[MeetingTime]`
The functional version doesn’t execute any IO action—its sole responsibility is to indicate that it will return a `List[MeetingTime]` and that somebody else will need to execute it (using `unsafeRunSync()` ). Therefore, one of the responsibilities is delegated to the client of `calendarEntries` or any other function that uses `calendarEntries` internally and returns an `IO` value as well.
> | val scheduledMeetingsProgram = scheduledMeetings("Alice", "Bob") ① → IO[List[MeetingTime]]① Nothing happened, we just got a description of a program as a value. |
Meanwhile, somewhere in the impure world, in the main process:
> | scheduledMeetingsProgram.unsafeRunSync() ① → List(MeetingTime(8, 10), MeetingTime(11, 12), MeetingTime(9, 10)) ① We executed IO actions that the given IO value describes and got some results. Remember that, since we are doing unsafe actions and haven’t discussed failure handling yet, this line can also result in an exception. Try again if that happens. |
Note how we used this new `scheduledMeetings` function that returns a description of a program (an `IO` value). Internally, this function uses a different description of a program ( `IO` values returned by `calendarEntries` ). No IO actions were executed when we called `calendarEntries` , and no IO actions were executed when we called `scheduledMeetings` . We just worked with `IO` values and got the `scheduledMeetingsProgram` value as the final version of the program. Then, finally, we just executed it. **It was the only impure line in the whole application** . The rest of the application is still purely functional because we only work with functions that operate on values.
This is how functional programs are designed. We will discuss it in more detail later in the chapter and again in chapter 11.
**The essence of FP is writing functions that transform input values into new output values** . We’ve been doing it since chapter 1. We’ve been working with `List` s, `String` s, `Set` s, `Option` s, `Either` s, and, now, with `IO` s, which are immutable values, just like the rest.
## The `IO` type is viral
One other very important consequence of using IO is that if we want to use a function that returns an IO inside a function we write, we are forced to return an IO value from that function as well! For example, when we developed the scheduledMeetings function, we knew that we needed to call calendarEntries for both person1 and person2 —otherwise, we wouldn’t be able to implement this requirement: | |
```
def scheduledMeetings(person1: String,
person2: String): IO[List[MeetingTime]] = {
for {
person1Entries <- calendarEntries(person1)
person2Entries <- calendarEntries(person2)
} yield person1Entries.appendedAll(person2Entries)
}
```
Notice that the return type is `IO[List[MeetingTime]]` , which is forced on us exactly because we use `calendarEntries` internally. There is no way around this. To do any computation on a value that is produced by an IO action (i.e., wrapped as an `IO` value), we need to produce a new `IO` value as well. (Using `unsafeRunSync` or other `unsafe` functions is forbidden, as they are not pure.) **The** `IO` **type is viral** ; once your function returns an `IO` , all other functions that use it will need to return an IO as well. It spreads, which has three important consequences.
THIS IS BIG!
When we use a function that returns an `IO` , we are forced to return an `IO` as well.
Use `IO` in as few places as possible
We’d like to give as much freedom to users of our functions as possible. Returning an IO is constraining because it makes them return an IO as well. Hence, we need to use IO sparsely. This chapter introduces IO , so we use it heavily, but, as we implement more things, notice how we try to extract most of the logic into pure non- IO functions. | |
`IO` acts as a tag for potentially failing cases
The good thing about `IO` being viral is that there is no way around it. That means it can help a lot in terms of identifying functionalities that need some special care—all functions that return `IO` s are functions that describe programs that may fail when executed. The `IO` type is therefore a highly visible tag in your codebase.
We will deal with failures and recovery strategies after solving the next exercise.
Nobody can hide unsafe side-effectful code
That all means that if your function doesn’t return an `IO` , we and all our teammates can be sure that it doesn’t create any unsafe side effects.
## Coffee break: Working with values 
To get you into the spirit of working with values (and recap some of the material from previous chapters), you are going to write the next major part of our meeting-scheduling app!
Your first task is to write the possibleMeetings function : def possibleMeetings(existingMeetings: List[MeetingTime], startHour: Int, endHour: Int,
lengthHours: Int): List[MeetingTime]It should return all the MeetingTimes , starting at startHour or later, ending at endHour or earlier, lasting lengthHours hours, and not overlapping with any existingMeetings . You already know everything to write such a function, but you may need to look through the List API docs to find a very handy function that creates lists containing a range of Ints . Documentation and API docs can be found at https://scala-lang.org/api/3.x/ . | 1 |
Using the function implemented in the previous step, implement the schedule function , which finds a free slot and, if found, returns the created meeting in Some , or None otherwise: | 2 |
Note the return type: `IO[Option[...]` \]! Use the fact that we are allowed to schedule meetings only inside working hours (8–16). Use the `scheduledMeetings` \* function you implemented earlier. You don’t have to persist the meeting using the API call yet. We’ll do that later, but as a bonus, try to think about how that might look.
scheduledMeetings * |
def scheduledMeetings(person1: String, person2: String): IO[List[MeetingTime]] = {
for {
person1Entries <- calendarEntries(person1)
person2Entries <- calendarEntries(person2)
} yield person1Entries.appendedAll(person2Entries)
} |
Tips and hints
Remember that in FP we work with values and declaratively transform them into new values. Try working on your own first, and don’t look at the hints or the answer before you have something:
1. The **`List`** class API has a **`range`** function that may help you generate a **`List`** of all possible starting hours. This may be used as a base for further transformations (e.g., to create a list of all possible **`MeetingTime`** slots \[remember **`map`** , `filter` , and `forall` ?\]).
2. It may be beneficial to go through the **`List`** API again and find out how to return an **`Option`** of the first element of the **`List`** .
## Coffee break explained: Working with values 
I hope you’ve put a lot of effort into solving this exercise. Remember that you learn the most in the long run when the learning process doesn’t feel easy! So don’t worry if you didn’t get it right on your first try. Have a look at the following solution, and find places where you struggled.
```
def meetingsOverlap(meeting1: MeetingTime, meeting2: MeetingTime): Boolean = {
meeting1.endHour > meeting2.startHour && meeting2.endHour > meeting1.startHour ①
}
def possibleMeetings(
existingMeetings: List[MeetingTime],
startHour: Int,
endHour: Int,
lengthHours: Int
): List[MeetingTime] = {
val slots = List
.range(startHour, endHour - lengthHours + 1) ②
.map(startHour => MeetingTime(startHour, startHour + lengthHours)) ③
slots.filter(slot =>
existingMeetings.forall(meeting => !meetingsOverlap(meeting, slot)) ④
)
}
def schedule(person1: String, person2: String, lengthHours: Int): IO[Option[MeetingTime]] = { ⑤
for {
existingMeetings <- scheduledMeetings(person1, person2)
meetings = possibleMeetings(existingMeetings, 8, 16, lengthHours) ⑥
} yield meetings.headOption ⑦
}
```
① We first create a helper pure function that will tell us whether two meeting times overlap.
② We use `List.range` to create a `List[Int]` , starting at startHour, and ending at the last possible start of a meeting of `lengthHours` . **We now have a list of all possible starting hours** .
③ Then, we map this `List[Int]` of all possible starting hours to a `List[MeetingTime]` .
④ Finally, given all possible slots, we filter out all slots that overlap with existing meetings, and voilà—we get a list of all possible meetings back!
⑤ We need to use values produced by unsafe `IO` actions—we know that because `scheduledMeetings` tells us this by having `IO` in its signature. So, just like working with values in the context of List or working with values in the context of `Option` , we use the `flatMap` power of the `IO` type inside a for comprehension to _extract_ and work on a value that will eventually be produced by `scheduledMeetings` .
⑥ `possibleMeetings` returns a List, so meetings is a `List[MeetingTime]` . We use `headOption` to take only the first element of this list (it will be `None` if the list is empty and `Some` otherwise).
⑦ `possibleMeetings` is a function that produces a value we want to use directly (it’s not contained in IO), so we use the equals sign. It works just like an assignment to a `val` , but we omit the `val` keyword when we are inside a for comprehension.
Congratulations! This exercise is one of the milestone exercises in the book. If you feel comfortable with your solution, it means you’ve mastered topics covered in chapters 5, 6, and 7. This will help a lot with the next topic we are going to cover, which is failure handling!
## Toward functional IO
Introducing `IO` solved the first of our problems: now the function describes a program that will execute some IO actions, but the responsibility for executing them is delegated to a different place in the application, chosen by its client. Somebody needs to call `unsafeRunSync()` eventually, but **it’s not a concern of the `schedule`** function anymore. `schedule` provides an `IO` value, and nothing happens until it’s _run_ (or _interpreted_ ).
> | val program = schedule("Alice", "Bob", 1) IO[Option[MeetingTime]]
program.unsafeRunSync()
Some(MeetingTime(10, 11)) |
If you are unlucky, you may need to run it multiple times before getting this answer. We’ll discuss it shortly.
The important thing is that we created a value that represents a rather complex program. We used many values that represent smaller programs and `mapped` and `flatMapped` them together. This is one of the key takeaways, not only of this chapter but of the whole book. At its core, **functional programming is about transforming immutable values using pure functions** .
THIS IS BIG!
FP is about transforming immutable values using pure functions, even when handling IO.
Current solution
def calendarEntries(name: String): IO[List[MeetingTime]] This function returns a description of a side-effectful IO action that, when executed, will return a list of MeetingTimes. def createMeeting(names: List[String], meeting: MeetingTime): IO[Unit] This function returns a description of a side-effectful IO action that, when executed, will not return anything (hence IO[Unit]). | | Both functions are just wrappers around potentially unsafe, sideeffectful IO actions defined in our unchangeable client library. We used IO.delay to make sure they are lazily evaluated later. |
def scheduledMeetings(person1: String, person2: String): IO[List[MeetingTime]] This function returns a description of a side-effectful IO action that, when executed, will return a list of MeetingTimes for two attendees. def schedule(person1: String, person2: String, lengthHours: Int): IO[Option[MeetingTime]] This function returns a description of a side-effectful IO action that, when executed, will return a possible MeetingTime. It is built using smaller descriptions (IO values), but no action is executed in this function. It's all just a combination of descriptions. |

## What about IO failures?
Now, let’s address the second problem we found at the beginning. We have already encountered it several times, but let’s recall what we are really facing here. The provided `calendarEntriesApiCall` function may fail (in our case—throw exceptions). We delegated the responsibility of running IO actions, but they still fail when they are run. That’s not good!

Note that this function is impure and unsafe because it doesn’t always return a result (sometimes it fails), and when it does, it’s not always the same for the same argument.
In the imperative solution, we tried to write a simple recovery strategy with one retry. Obviously, some more sophisticated strategies are available, but the point here is that their implementations should not entangle with the business logic too much. We don’t want to have a dozen lines of recovery code entangled with a single line of business logic! It’s a different responsibility.
Problem 2
**If any of the three external API calls fails, the whole function fails** .
If there is any problem in the API call (network error, server error, etc.), the whole function fails with an exception, which may be confusing to the user. From the business logic perspective, we cannot assume anything about any API calls.
```
List
person1Entries = null;
try {
person1Entries = calendarEntriesApiCall(person1);
} catch(Exception e) {
person1Entries = calendarEntriesApiCall(person1);
}
```
Earlier in the chapter we implemented a simple recovery mechanism that retries the same call once if it fails. The same needs to be written for other API calls as well!
In imperative programming we program recipes : step-by-step guides for the processor to execute. That’s why recovery code is often intertwined between business logic lines, making the whole thing unreadable and unmaintainable in the long run. In FP, we use declarative style —describing what we want and delegating the responsibility to execute our wishes. That gives us many design superpowers because we can build programs using compatible blocks (values). Surprisingly, we have already covered a function that we’ll use to build recovery strategies. Quick question: do you remember how we transformed an Option value that might have potentially been None ? | Answer: Option.orElse
|
## Running a program described by `IO` may fail!
Since our IO actions may sometimes fail (as is the case with the majority of side-effectful IO calls), programs that are based on them may fail as well! Wrapping unsafe calls as an `IO` value guards us from immediate failures. We decoupled the description of a program ( `IO` value) from its execution (calling `unsafeRunSync(` )), so we won’t get any failures as long as we stay in the context of `IO` . Thus, calling these functions is guaranteed to be safe and won’t ever fail—they just return values!
```
def calendarEntries(name: String): IO[List[MeetingTime]]
def createMeeting(names: List[String], meeting: MeetingTime): IO[Unit]
def scheduledMeetings(person1: String, person2: String): IO[List[MeetingTime]]
def schedule(person1: String, person2: String, lengthHours: Int): IO[Option[MeetingTime]]
```
These functions will never fail!
However, that doesn’t mean we are completely safe. If the underlying IO actions randomly fail (as is the case with our unchangeable `calendarEntriesApiCall` , which has a failure rate at around 25%), our programs may fail when descriptions ( `IO` values) get executed. If you’ve been following along in your REPL, you’ve probably seen it already.
```
val program = schedule("Alice", "Bob", 1)
→ IO[Option[MeetingTime]]
program.unsafeRunSync()
→ Exception in thread "main": Connection error
```
Note that the program described by the `IO` value returned by the `schedule` function may contain several unsafe API calls. They all need to succeed for the whole execution to succeed.
However, _sometimes_ the underlying actions may all succeed, so we should eventually get lucky if we try again and again.
```
program.unsafeRunSync() ①
→ Exception in thread "main": Connection error
program.unsafeRunSync() ②
→ Some(MeetingTime(10, 11))
```
① Not this time!
② Since `program` is just an immutable value, we can reuse it and run it as many times as we want. This time it worked, and we got a result!
So it’s clear that if an IO action is unsafe and may fail, so can the program described by the `IO` value that calls this action. This can happen only after an `IO` value is run using `unsafeRunSync()` , not earlier (again, because earlier it’s just a value). Even though we disentangled the execution from the description, we still need to _declare_ what happens in case of a failure. We still need a way to describe a recovery mechanism, like a single retry. Fortunately, **we can encode a recovery mechanism inside an `IO` value too!** And this can be a very sophisticated recovery mechanism, too! We will use a familiar function to do it.
## Remember `orElse` ?
`IO` type gives us the ability to describe what should be used if something fails, just like `Option` and `Either` give us the ability to describe what should be used if they are `None` or `Left` . Just like `Option` and `Either` have `orElse` , **`IO` has it too** !
The `IO` type is part of the cats-effect library. To use `IO` , you need to import `cats.effect.IO` first. To use `orElse` , which is a generic function, you need to import `cats.implicits._` as well. Again, everything is already imported for you if you use `sbt console` from the book’s repository.
The main difficulty of grasping `IO` is changing the mental model from _running IO code_ to _having a value that describes IO-based code._ Once you grok it, everything becomes easier because you are able to tap into intuitions that have already been built. With failure handling, the intuition is that `IO` is really similar to `Option` and `Either` , among others. When you need to recover from something that doesn’t belong to your program’s happy path, you use `orElse` , which creates a new value. Let’s see this for ourselves.
| Option.orElse | | Either.orElse |
> | val year: Option[Int] = Some(996) val noYear: Option[Int] = None
year.orElse(Some(2020))
→ Some(996)
noYear.orElse(Some(2020))
→ Some(2020)
year.orElse(None)
→ Some(996)
noYear.orElse(None)
→ None | > | val year: Either[String, Int] = Right(996)
val noYear: Either[String, Int] = Left("no year")
year.orElse(Right(2020))
→ Right(996)
noYear.orElse(Right(2020))
→ Right(2020)
year.orElse(Left("can't recover"))
→ Right(996)
noYear.orElse(Left("can't recover"))
→ Left("can't recover") |
| IO.orElse Look for similarities in outputs. Some and Right values are similar to successful IO value executions. None and Left values are similar to failed IO value executions! |
> | val year: IO[Int] = IO.delay(996) val noYear: IO[Int] = IO.delay(throw new Exception("no year")) ①
val program1 = year.orElse(IO.delay(2020))
→ IO[Int]
val program2 = noYear.orElse(IO.delay(2020))
→ IO[Int]
val program3 = year.orElse(IO.delay(throw new Exception("can't recover")))
→ IO[Int]
val program4 = noYear.orElse(IO.delay(throw new Exception("can't recover")))
→ IO[Int]
program1.unsafeRunSync() ②
→ 996
program2.unsafeRunSync()
→ 2020
program3.unsafeRunSync()
→ 996
program4.unsafeRunSync()
→ Exception in thread "main": can't recover ③① noYear is a description of a program that, if successful, will return an Int . However, we see that it will always fail when we run it! So how can we recover? ② Up until this point we have only created IO values, so both year and noYear are values. program1, 2, 3, and 4 are also just values. Some of these values, however, incorporate a simple failure recovery strategy! We can see it by running programs described by these values using unsafeRunSync() . ③ The exception message is from the IO value passed to orElse . Running noYear failed, so the one from orElse was used and failed as well. |
## Lazy and eager evaluation
The behavior of `IO.orElse` is very similar to what we had with both `Either` and `Option` . `orElse` gets another `IO` value that is used only if the original one is _not successful_ . `Option's` unsuccessful case is `None` , `Either` 's is `Left` , and `IO` 's is a side-effectful IO action that fails (throws an exception) after it’s executed.
Here’s yet another way to look at how `orElse` works:

`orElse` needs an `IO` value as its parameter, just like `Option.orElse` needs an `Option` and `Either.orElse` needs an `Either` . Did you notice how, this time, we used `IO.pure` to produce an `IO` that always succeeds with a hardcoded value?
```
val alwaysSucceeds: IO[Int] = IO.pure(42)
```
As the name suggests, the code we pass to `IO.delay` is not evaluated (it’s _delayed_ ) until we call `unsafeRunSync()` on this `IO` or another `IO` value that uses this `IO` . On the other hand, `IO.pure` **evaluates** the given code (in this case `42` ) **immediately** and saves it inside an `IO` value. This is a great example of the difference between lazy and eager evaluation.
The code we pass to `IO.delay` is “stored" in a similar way closures are stored for later use. In case of `IO` , they are only executed once someone calls `unsafeRunSync()` .
Lazy evaluation | Eager evaluation |
Lazy evaluation of an expression is a delayed evaluation—it’s not evaluated until it’s really needed somewhere. Function bodies are lazily evaluated. The code you write inside a function is not executed until the function is called. Code passed to IO.delay is also lazily evaluated. The following will always succeed (both value creation and unsafeRunSync() call.) val program = IO.pure(2022).orElse( IO.delay(throw new Exception()) ①
)
→ IO[Int]
program.unsafeRunSync()
→ 2022 ① This will never get executed! | Eager evaluation of an expression is an immediate evaluation—the code is executed (evaluated) in the same place it’s defined, immediately. Value definitions are eagerly evaluated. The code you write on the right side of the equals sign is executed rightaway. Code passed to IO.pure is also eagerly evaluated. The following will fail at the value creation because the code is eagerly evaluated and always throws an exception. val program = IO.pure(2022).orElse(
IO.pure(throw new Exception())
)
→ Exception thrown The exception is evaluated eagerly—we didn't even call unsafeRunSync because we had no value to call it on! |
The same techniques are used in `IO` types from other functional languages!
## Implementing recovery strategies using `IO.orElse`
Let’s first implement the _single retry_ strategy we implemented imperatively using try-catches but this time using `IO` and its `orElse` function. It should be pretty straightforward knowing what we know.

And that’s it! The good news is that once you get accustomed to IO being just a value, it becomes very easy to implement many—supposedly complex—strategies, involving not only retries but also fallbacks, backoffs, and cached values, some of which we’ll see later in the chapter. orElse works as one may expect, having had only some exposure to Either and Option . That’s a big win too, you must agree. One more important thing to discuss is that orElse returns IO , which means we can chain orElse calls as many times as we want to create bigger, more complicated IO values from smaller ones. We’ll use this a lot, but before we do, let’s make sure we are on the same page. Quick exercise Write down an expression that creates an IO value that describes a program that will retry calendarEntries two times. | Answer: calendarEntries(...)
.orElse(
calendarEntries(...)
).orElse(
calendarEntries(...)
)
|
## Implementing fallbacks using `orElse` and `pure`
Let’s use the power of `orElse` chaining with lazy and eager evaluation of `IO` constructors ( `IO.delay` and `IO.pure` , respectively) to create a more complicated recovery strategy encoded as a _single_ `IO` value. We can use `IO.pure` as a last call in our `orElse` chain because we know it will always succeed. We know it will always succeed because the expression we pass to `IO.pure` is evaluated eagerly. When we use a value created using `IO.pure` as an argument to the last `orElse` call in the chain, we get ourselves an `IO` value that, when executed, **will never fail** . That’s how we can implement yet another recovery strategy that first does a retry, and if it fails again, it uses a **safe fallback value** .
Problem 2
**If any of the three external API calls fails, the whole function fails** .
```
calendarEntries("Alice")
.orElse(calendarEntries("Alice"))
.orElse(IO.pure(List.empty))
```
An `IO` value that describes the following behavior: call the side-effectful IO action, and return results if it’s successful. If it fails, retry max one time. If the retry fails, return an `IO` value that will always succeed and return an empty list.

Q Is it OK to just return an empty list if the call to an external API fails two times in a row?
A It depends! Note that right now we are just discussing tools that we can use to implement different failure recovery strategies. However, it’s very important to understand how these strategies may affect business logic. Returning an empty list may or may not be OK in a given business context. We will continue discussing this trade-off when we cover functional architecture in more depth later in the chapter.
We’ll discuss it soon in the “Functional architecture" section.
To sum it up, all of the following are values that describe different programs that have different failure recovery behaviors.
```erlang
calendarEntries("Alice") ①
.orElse(calendarEntries("Alice"))
calendarEntries("Alice") ②
.orElse(IO.pure(List.empty))
calendarEntries("Alice") ②
.orElse(calendarEntries("Alice"))
.orElse(calendarEntries("Alice"))
.orElse(IO.pure(List.empty))
```
① An `IO` value that describes the following behavior: call the side-effectful IO action, and return results if it’s successful. If it fails, retry max one time.
② An `IO` value that describes the following behavior: call the side-effectful IO action, and return results if it’s successful. If it fails, return an `IO` value that will always succeed and return an empty list.
③ An `IO` value that describes the following behavior: call the side-effectful IO action, and return results if it’s successful. If it fails, retry max two times. If all retries fail, return an `IO` value that will always succeed and return an empty list.
## Practicing failure recovery in `IO` values 
It’s time you try writing some code on your own. Here are two functions that return an `int` in Java and are not pure functions.
| |
import ch08_CardGame.castTheDie | import ch08_CardGame.drawAPointCard ① These are impure and unsafe functions that may throw exceptions. They are written in Java as a convention we use in the book. We are wrapping them in Scala functions that you can conveniently import into your REPL session. |
Your task is to create three different `IO` values that describe the following programs:
1. Cast the die, and if it fails to produce a result, return 0.
2. Draw a card, and if it fails, cast the die.
3. Cast the die, and if it fails—retry once. If it fails again, return 0.
4. Cast the die, and draw a card, using a fallback of 0 for each of them. Return the sum of both.
5. Draw a card, and cast the die twice. Return the sum of all three or 0 if any of them fails.
Hint: Remember that everything in FP is an expression that produces a value.
Answers
IO.delay(castTheDie()).orElse(IO.pure(0)) | 1 |
IO.delay(drawAPointCard()).orElse(IO.delay(castTheDie())) | 2 |
IO.delay(castTheDie()) .orElse(IO.delay(castTheDie()))
.orElse(IO.pure(0)) | 3 |
for {
die <- IO.delay(castTheDie()).orElse(IO.pure(0))
card <- IO.delay(drawAPointCard()).orElse(IO.pure(0))
} yield die + card | 4 |
(for {
card <- IO.delay(drawAPointCard())
die1 <- IO.delay(castTheDie())
die2 <- IO.delay(castTheDie())
} yield card + die1 + die2).orElse(IO.pure(0)) ①① This for expression produces an IO value as well. We can therefore use orElse on the whole value and have a wider fallback. | 5 |
## Where should we handle potential failures?
Do you remember the multiple try-catches we needed to handle potential failures in the imperative code? Now compare this to the following `IO` -based different possible versions that use a single retry and a default value in case anything (including retries) fails. Whatever we choose, there is not much overhead because we operate on values, and we can implement failure handling on any level we need and want.
Yes, it’s still not a perfect solution, but it shows failure-handling logic. We will build an even safer version soon, using the same concepts!
1 | The first option is to implement failure handling in calendarEntries. Then, we don’t need to change schedule at all: |
```
def calendarEntries(name: String): IO[List[MeetingTime]] = {
IO.delay(calendarEntriesApiCall(name))
.orElse(IO.delay(calendarEntriesApiCall(name)))
.orElse(IO.pure(List.empty))
}
```
2 | The second option is to implement failure handling at the level of the scheduledMeetings helper function: |
```
def scheduledMeetings(person1: String,
person2: String): IO[List[MeetingTime]] = {
for {
person1Entries <- calendarEntries(person1)
.orElse(calendarEntries(person1))
.orElse(IO.pure(List.empty))
person2Entries <- calendarEntries(person2)
.orElse(calendarEntries(person2))
.orElse(IO.pure(List.empty))
} yield person1Entries.appendedAll(person2Entries)
}
```
3 | The third option is to implement failure handling at the level of the schedule function: |
```
def schedule(person1: String, person2: String,
lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(person1, person2)
.orElse(scheduledMeetings(person1, person2))
.orElse(IO.pure(List.empty))
meetings = possibleMeetings(existingMeetings, 8, 16, lengthHours)
} yield meetings.headOption
}
```
You can use any of the three approaches above or mix them up! The final decision depends on many factors, including business logic context and general architecture of handling failures. The key takeaway is that you have lots of possibilities by using IO values alone. We will choose the third one for now. | |
## Toward functional IO with failure handling
Introducing `IO` has already solved two of the three problems we encountered in the imperative solution earlier in the chapter. We now have code that is able to handle failures by describing complicated recovery strategies without impeding the business logic flow (that, in turn, has a major impact on readability and maintainability). We compared the functional way to the imperative Java version, where the business logic got lost inside many lines of try-catches and related mechanisms.
```
def schedule(person1: String, person2: String,
lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(person1, person2)
.orElse(scheduledMeetings(person1, person2))
.orElse(IO.pure(List.empty))
meetings = possibleMeetings(existingMeetings, 8, 16, lengthHours)
} yield meetings.headOption
}
```
Remember that our solution still doesn’t persist any meetings—it doesn’t call one of the required `createMeetingApiCall` functions—when it finds a free slot. We will deal with that at the end of the chapter.
This problem will also be solved as an `IO` value, but since this is an output action, we need to discuss some caveats around it.
Failure vs. errors
Have you noticed that we’ve been discussing failures—not errors— in this chapter? When we say _failure_ , we usually mean a problem that presents itself when running some unsafe, side-effectful code: connection dropped, server unexpectedly failed, and so on. We use _error_ to indicate some business-level errors, such as _user provided wrong password_ or _provided `String` cannot be parsed_ . In chapter 6 we discussed error handling—there were no failures there!
We can, however, transform a failure into an error, explicitly, by transforming one value into another, of course. We’ll show that in the last part of the book.

## Pure functions don’t lie, even in the unsafe world!
Problem 3
**The signature lies** .
The third problem with the initial imperative solution we wrote was related to the old notion that we’ve been exercising since the beginning of the book. Compare the following two function signatures. The first signature is the imperative version, while the second is the functional `IO` -based version we’ve been tuning for a while. Which difference is the most obvious one?
Imperative
```
static MeetingTime schedule(String person1, String person2, int lengthHours)
```
Functional
```
def schedule(person1: String, person2: String, lengthHours: Int): IO[Option[MeetingTime]]
```
The signatures look similar; they both take three parameters, but they return a different thing: the imperative version returns a `MeetingTime` , while the functional version returns an `IO[Option[MeetingTime]]` . Which one lies, and which one tells the truth?

That was a leading question, wasn’t it? We already know that the imperative `schedule` won’t always return a `MeetingTime` , although it promises in the signature that it will! There are two ways in which it won’t deliver on its promise:
1. There is a connection error retrieving calendar entries for a person, then the function throws an exception instead of returning a **`MeetingTime`** .
2. There is no common slot for a meeting of length **`lengthHours`** to be scheduled for both attendees, then the function returns **`null`** , which is not exactly a **`MeetingTime`** it promises us.
Now, compare this to the functional signature, which doesn’t lie and always, no matter what, returns an `IO[Option[MeetingTime]]` . It tells us that this function **returns a value that describes a program tha** .
- Does some IO actions, which may potentially be side-effectful and fail for many reasons, including that they are dependent on the outside world (IO).
- When it’s executed (later in the program) and succeeds, it will return an **`Option[MeetingTime]`** , which means that we need to take into consideration a possibility of **`MeetingTime`** not being there. Note that the signature forces us to handle this possibility by returning an **`Option[MeetingTime]`** . \*
\* If there were more than one possibility of business-related problems (not just a lack of a common slot), we might use `Either[String, MeetingTime]` to further describe such a possibility.
## Functional architecture
Our software needs to do unsafe IO actions. But we also want to have as many pure functions as possible! We’ve been pondering the idea of a functional architecture since the beginning of the book. Since we’ve just learned about `IO` values, we can fully discuss how all pure and impure functions may work with each other inside a single software solution.

The black arrows in the diagram indicate a _knows about_ relation. That means all the functions inside the _functional core_ can’t directly access functions from the outside.

Q How is it possible to achieve? The `calendarEntriesApiCall` inside it, so it clearly knows about it! What’s going on?
A So far we’ve defined `calendarEntries` and `createMeeting` as functions that directly call impure functions (wrapping them in `IO.delay` ). However, we may use a different strategy and **pass these functions as parameters** ! Then, the functional core knows only about their signatures, while the implementation is provided from the outside! We can say that we “configure" functions inside the functional core. We’ll cover it next.
THIS IS BIG!
We push the impurity out of the functional core, so it’s easier to test and maintain.
This is a very common pattern in FP. We extract all the possible business-related logic into pure functions that don’t lie, bundle them together as a functional core, test them separately, then use them in the main process. This way the concerns are becoming more and more disentangled. **That is the foundation of the functional architecture** .
## Using `IO` to store data
So far we’ve focused mostly on input actions—side-effectful actions that read values from the outside world. The `schedule` function implementation is still missing one final piece, which I’ll ask you to do in the next exercise. Before this happens, we need to show how to handle output actions (i.e., side-effectful actions that write \[or store, persist\] values for later use). Fortunately, it doesn’t differ much from what we’ve learned about input actions. Let’s write a function, that returns a _description_ of a program, that:
1. Gets a first name from the outside world
2. Gets a second name from the outside world
3. Finds a two-hour meeting slot for both names
4. Shows an `Option[MeetingTime]` when executed
5. Doesn’t return any value
Note that we don’t specify how the input is provided to the program. This is an important piece. We are leaving this decision to the client of our function.
We obviously can use the unfinished `schedule` function to find and return a potential meeting, but the most important things are the first three requirements. Let’s do a step-by-step implementation of this function, which we’ll call `schedulingProgram` . Treat this also as an example of a simple functional architecture that we’ve just discussed.
We’ll cover the functional core idea in more depth in the last chapters of the book. Here, we’ll just show how we can pass functions as parameters to “configure" a program.
❶ | We start with the signature. Based on the requirements above, we can write: |
```
def schedulingProgram(
getName: IO[String], ①
showMeeting: Option[MeetingTime] => IO[Unit] ②
): IO[Unit] = { ③
}
```
① Our program needs to be able to get names from the outside world. That means it needs a description of a program that gets a `String: IO[String]` .
② Our program needs to be able to show a potential meeting. That means it needs a function that gets an `Option[MeetingTime]` and returns a description of a program that somehow shows it without doing anything more. Therefore, we expect that the client of the `schedulingProgram` function will provide a function `Option[MeetingTime] => IO[Unit]` .
③ This function returns a program that, when executed, doesn’t return anything ( `Unit` ). Remember that Scala’s version of the type void is `Unit` (you may think of it as a singleton type that only has one value). When a function returns an `IO[Unit]` , we can assume that it exists only to describe some side effects. We may assume that this is an `IOheavy` program (and lack of any result means we expect some kind of output action to happen—in this case we expect that it will _show_ a meeting when executed). This function describes an **output action** .
❷ | We will work in the context of IO and order all actions sequentially; we’ll need to use for comprehensions ( flatMap ): |
```
def schedulingProgram(
getName: IO[String],
showMeeting: Option[MeetingTime] => IO[Unit]
): IO[Unit] = { ①
for {
} yield () ②
}
```
① We will now implement all the sequential operations inside this for comprehension.
② We are `yield` ing (), which is the only value of type `Unit` . This is a common expression when describing side-effectful output actions.
❸ | The first two steps of the program is to get two names from the outside world: | |
```
def schedulingProgram(
getName: IO[String],
showMeeting: Option[MeetingTime] => IO[Unit]
): IO[Unit] = {
for { ①
name1 <- getName ①
name2 <- getName ①
} yield () ①
}
```
① This is an expression that produces an IO\[Unit\] value that consists of two smaller programs (getName programs). When executed, this will execute the getName program twice and, if successful, will provide two `String` values: `name1` and `name2` .
❹ | Then, the next step is to call the schedule function, which takes two Strings and the lengthHours integer: |
```
def schedulingProgram(
getName: IO[String],
showMeeting: Option[MeetingTime] => IO[Unit] ①
): IO[Unit] = {
for {
name1 <- getName
name2 <- getName
possibleMeeting <- schedule(name1, name2, 2) ②
} yield ()
}
```
① The schedule returns an `IO[Option[MeetingTime]]` , and since we are using `flatMap (<-` in the for comprehension), we extract `Option[MeetingTime]` and save it as `possibleMeeting` value.
② Remember how `flatMap` works? Essentially, each step is done sequentially, assuming all the previous steps succeeded. A failure is desined differently, depending on the type we are working with. For List it's List.empty, for `Option` it's `None` , for `Either` it’s `Left` , and for `IO` —a description of a program that fails when executed.
❺ | The last step is to show the meeting using a description of a program that is passed as a parameter: |
```
def schedulingProgram(
getName: IO[String],
showMeeting: Option[MeetingTime] => IO[Unit]
): IO[Unit] = {
for {
name1 <- getName
name2 <- getName
possibleMeeting <- schedule(name1, name2, 2)
_ <- showMeeting(possibleMeeting) ①
} yield ()
}
```
① `showMeeting` is a function that returns an `IO[Unit]` . That means that we call it only to make sure its side effects are executed as a part of this program. We know that it will always return a value of type `Unit` (which has only one value: `()),` so we save it as \_ which in Scala means _an unnamed value_ .
❻ | We now have a full implementation of the new program. The client can choose where and how this program gets names and how it outputs them. Let’s assume that we want to use these two imported functions: |
def consolePrint(message: String): Unit | import ch08_SchedulingMeetings.consolePrint |
| import ch08_SchedulingMeetings.consoleGet |
These two impure, imperative functions use console to get and print Strings . We want to use them as both input and output actions of the scheduling program above. Is it possible? How would you approach that . | |
❼ | Now, we are far outside the functional core. We want to use the new schedulingProgram function and configure it to use console as both user input and output. (Configuring is just a fancier name for passing arguments to a function!) Note that the schedulingProgram function doesn’t know anything about impure functions it calls. This is a concern of its client. It could configure it to use HTTP or a GUI, or even something different like stubbed values in tests (using IO.pure , for example!). schedulingProgram knows only as much as it should. |
```
def consolePrint(message: String): Unit ①
def consoleGet(): String ②③
schedulingProgram( ④
IO.delay(consoleGet()),
meeting => IO.delay(consolePrint(meeting.toString))
).unsafeRunSync()
```
① Prints a given message to the console output
② Gets a single line from the console input
③ We use the two impure, imperative functions that use `console` and wrap them in `IO.delay` . The first parameter is an IO value we create directly. The second is a function, so we pass an anonymous function as an argument.
④ We call `schedulingProgram` with these arguments, and we get an `IO[Unit]` value back, which is a `console` -based scheduling app.We then run it using `unsafeRunSync()` .What we get is a program execution that waits for two names to be read from the console and then prints a `Some` or `None` value, depending on what names were given and what `calendarEntriesApiCall` returned (or an empty list if it failed two times).
That’s all! We’ve written another small function that is very versatile. It returns an IO[Unit] , so we know it’s heavy on side effects, and its main responsibility will be to output something important in a way that is required by the user. It could be a console application, like we showed, or something totally different. It doesn’t really matter as far as the schedulingProgram implementation is concerned. The function, through its signature, requires its clients to choose the IO actions implementation themselves. We could say that concerns are disentangled: the schedulingProgram concern is the sequence of operations (get two names, run scheduling program, and show the result), while the concern of its client (and probably the main application process) is to choose the interface. One way to look at this is that schedulingProgram represents an essential concern , while the rest is an accidental concern . | |
Remember, you need to provide a configuration of thread pools that will be used to execute an `IO` (done automatically in our REPL). It’s also done outside of the functional core!
FP provides tools that allow you to disentangle concerns in your specific application. However, the most difficult job still lies in your hands: deciding what are essential concerns (directly related to your business domain) in your application and what are accidental ones. In the `schedule` function we’ve implemented, you may say that the retry logic is not an essential concern: the crucial thing is that we get a value. And that may be true. However, if we add a fallback value, doesn’t it impact the business logic at least a little bit? It probably does, so it may be essential after all. There are no universal answers to this question, and I won’t try to provide one. What’s important is that concerns are visible in the code, preferably in pure function signatures. You should aim to put as many essential concerns as possible inside pure functions, and they should be the core of your application—the **functional core** .
THIS IS BIG!
In FP, we strive to put as many essential concerns as possible inside pure functions.
For more information about this I recommend reading the “Out of the Tar Pit" paper (Moseley & Marks, 2006.)
## Coffee break: Using `IO` to store data 
There is still one thing that we haven’t solved yet in our original problem. Here’s the `schedule` function we’ve implemented so far:
```
def schedule(person1: String, person2: String,
lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(person1, person2)
.orElse(scheduledMeetings(person1, person2))
.orElse(IO.pure(List.empty))
meetings = possibleMeetings(existingMeetings, 8, 16, lengthHours)
} yield meetings.headOption
}
```
And here are the requirements we were tasked to implement at the beginning of this chapter.
Requirements: Meeting scheduler
1. For given two attendees and a meeting length, your function should be able to find a common free slot.
2. Your function should persist the meeting in the given slot in all attendees’ calendars.
3. Your function should use impure functions that talk with the outside world, **`calendarEntriesApiCall`** and **`createMeetingApiCall`** without modifying them. (Assume they are provided by some external client library.)
See? We’ve implemented the first requirement and part of the third one! You now need to add the functionality to persist a potential meeting using the provided side-effectful `createMeetingApiCall` function without changing it.

We already created a function that should be used in this case, but we haven’t used it yet. It’s called `createMeeting` , and it returns an `IO[Unit]` value. It describes a program that, when executed, will call the impure API function that stores the given meeting for given names (see left). You should be able to quickly recreate it in this exercise if it’s not already in your REPL.
**Your task is to change the `schedule` function above,** so it returns a program that not only finds and returns a potential meeting but also stores it for later, using the provided output action. **As a bonus exercise,** think about a recovery strategy for a `createMeeting` call. Please take your time, and try to solve it before looking at the answer.
Hint: Remember that `Unit` has only one value: `()` . You can use `IO.pure(())` as an `IO[Unit]` value. Also, check out the `IO.unit` function.
## Coffee break explained: Using `IO` to store data 
One of the possible solutions can be written using only the things we’ve learned so far, including pattern matching!
```
def schedule(person1: String, person2: String, lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(person1, person2)
.orElse(scheduledMeetings(person1, person2))
.orElse(IO.pure(List.empty))
meetings = possibleMeetings(existingMeetings, 8, 16, lengthHours)
possibleMeeting = meetings.headOption ①
_ <- possibleMeeting match { ②
case Some(meeting) => createMeeting(List(person1, person2), meeting) ②
case None => IO.unit // same as IO.pure(()) ②③
} ②
} yield possibleMeeting
```
① First, we need to create another value, meetings, which is a list returned by `possibleMeetings` . Remember that `possibleMeetings` returns a `List[MeetingTime]` (not wrapped in an IO because it doesn’t do any IO!), so we need the = operator. We use `headOption` on this list to return the first meeting wrapped in `Some` , or `None` if the list is empty.
② Value of type `IO[Unit]`
③ Then we pattern match on `possibleMeeting` , which is an `Option[MeetingTime]` . Note that the whole pattern matching expression needs to be an `IO` value (because we are in the for comprehension that works on `IO` values, plus we use the `<-` operator). Both cases should return values of the same type—in our case, it’s an `IO[Unit]` . If a meeting is found `(case Some(meeting))` , the expression becomes an `IO[Unit]` value created by calling the `createMeeting` function. If no meetings are found ( `case None` ), the expression becomes an IO.unit value, which is a pure `IO[Unit]` value (evaluated eagerly). It will always succeed and won’t do any side effects when executed. This way the whole pattern matching expression has type `IO[Unit]` and compiles fine. It will also do the right thing when executed: it will call the `createMeetingApiCall` function only when a meeting is found.
Bonus exercise
Note that the solution above provides a program that may fail if a call to `createMeetingApiCall` fails. But since `createMeeting` returns an `IO` value, we can use exactly the same approach (i.e., `IO.orElse` ) to produce values that describe programs with some recovery strategies built in. For example:
```
case Some(meeting) => createMeeting(List(person1, person2), meeting)
.orElse(createMeeting(List(person1, person2), meeting)
.orElse(IO.unit)
```
However, **output actions may change data stored externally** , so retrying them may not be the most safe approach, especially if these operations are not _idempotent_ (i.e., can't be applied multiple times without changing the final result).
And it’s solved! We’ve managed to write a function that implements all requirements. Note how few lines were needed to implement this logic. It contains the step-by-step flow and calls external APIs with simple recovery strategies and safe fallbacks. It also says a lot about itself in its signature. That’s the power of functional programming!
## Treating everything as values
At this point you should be very competent treating IO-based code as values. We’ve shown a real problem and its functional solution that takes advantage of all the tools and ideas we learned in previous chapters.

Q OK, treating `IO` as values looks very useful, but I still feel this is too good to be true. There are multiple more IO-based problems that surely can’t be addressed using this approach, can they?
A You are in for a treat! We will spend the rest of the book showing even more advanced examples solved using the tools we’ve introduced here. We will play around with retries and executing an unknown number of programs before we wrap up this chapter. Then, we will talk about data streams and message-based systems. We are going to represent them as `IO` values as well. In chapter 10 we will address problems related to asynchronous and multithreaded computing. We will use `IO` values there, too!
Caching and using cached values in case of a failure \*
Let’s show how we can use `IO` in three more scenarios related to the meeting scheduler example. The first one is **caching** . Our current solution would definitely benefit from using a cache for scheduled meetings, so we can get a cached value when an API call fails. Generally, this is a topic we will discuss in depth later because there are multiple additional problems we need to consider, such as removing stale values from the cache, updating values in the cache, making sure the caches are consistent, and many others. Here, we will briefly show how could it be implemented using the `IO` type. **The whole solution is just three more functions** :
`calendarEntries`
Wrapper around impure API call. Returns a description of a program that returns a list of meetings for a given name.
\* Phil Karlton’s wise saying is, “There are only two hard things in computer science: cache invalidation and naming things." We’ll deal with caching later in the book. Here, we just present a sneak peek.
```
def cachedCalendarEntries(name: String): IO[List[MeetingTime]]
def updateCachedEntries(name: String,
newEntries: List[MeetingTime]): IO[Unit] ①
def calendarEntriesWithCache(name: String): IO[List[MeetingTime]] = {
val getEntriesAndUpdateCache: IO[List[MeetingTime]] = for {
currentEntries <- calendarEntries(name)
_ <- updateCachedEntries(name, currentEntries)
} yield currentEntries
cachedCalendarEntries(name).orElse(getEntriesAndUpdateCache)
}
```
① We don’t show the implementation but you will be able to code it after reading chapter 10. Note that these two functions need to use the same mutable data store. It can be an in-memory variable or an API like Redis or `memcached` .
## Treating retries as values
The second small improvement we can make to the meeting scheduler is a more universal approach to retries. So far we’ve been retrying once and then falling back to an empty list:
```
scheduledMeetings(person1, person2)
.orElse(scheduledMeetings(person1, person2))
.orElse(IO.pure(List.empty))
```
But what if wanted to use 3 retries, or 7, or 10? Would we need to write `orElse(scheduledMeetings(person1, person2))` 10 times? That would work, but it wouldn’t be a very handy or readable solution. Moreover, the number of retries is usually passed from an environmental variable or a configuration file (i.e., from the _outside_ ). So we can’t really use this approach. We need to retry a given, unknown, number of times. We need **configurable retry strategies** .
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] ①
```
① Note that the `retry` function doesn’t care what `A` type is because it is not going to work with its values at all. It will only work with the `IO` value and the `Int` value. So `A` can be a `List` , an `Int` , a `String` , a `Unit` , or even another `IO` . Anything.
This new `retry` function is generic with regard to the type, just like a `List[A]` is. It takes a value named `action` , which has type `IO[A]` —a description of an action that produces a value of type `A` and a maximum number of retries when this action fails (the `maxRetries` parameter). Note that the function returns another description of a program that, when executed successfully, returns a value of type `A` . Before we implement it, let’s see how can we would use it.
```
retry(scheduledMeetings(person1, person2), 10) ①
.orElse(IO.pure(List.empty))
```
① `scheduledMeetings(person1, person2)` is the `IO` value that represents a program we want to retry. If it fails, it is going to be retried a maximum of `10` times. If all retries fail, we will return an empty list using `orElse` .
So how can we implement the `retry` function? You already know every tool and mechanism we need to do it. But it still may not be clear to you how to approach this problem. **The key here is to start thinking in terms of values** . We need to think about a list of programs in exactly the same way we thought about a list of possible meeting slots.
THIS IS BIG!
Functional programmers treat everything as values.
❶ | Let’s start simple. If we wanted to retry maximum once, we’d need the following: |
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] = { ①
action.orElse(action) ②
}
```
① We will approach this implementation gradually and use the help of our old friend: the compiler.
② Our first approach to writing the `retry` function is to ignore the `maxRetries` parameter and use a fixed number of retries: in this case we use `orElse` once, so if the `action` fails, this function will retry a maximum of one time.

❷ | Generally, if we wanted to retry a fixed number of times, we’d need a fixed amount of orElse s: |
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] = {
action.orElse(action).orElse(action).orElse(action) ①
}
```
① Here, we use `orElse` three times, so that means a program described by the action value, in case it fails three times in a row, will be retried three times. This is the outcome we want when we pass `maxRetries = 3` .
❸ | Now, let’s switch the mindset to the value-based one. We know that if we want to retry a maximum of one time, we need a value produced by calling orElse once. When we want to retry a maximum of three times, we need a value produced by calling orElse three times. Therefore, to implement the real version of retry , we need a value produced by calling orElse maxRetries times. We can achieve this by creating a list of maxRetries elements first. |
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] = { ①
List.range(0, maxRetries) ①
}
```
① Note that this doesn't compile yet, because types don't match.
② List.range creates an incremental list of integers, starting with the value provided as the first argument and ending with an integer one smaller than the one provided as the second argument. So, for `maxRetries = 3` we’d get the `List(0, 1, 2)` .
❹ | Now we have a list with the exact amount of retries we need. But we don’t need integers, we need actions themselves. Enter map : |
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] = {
List.range(0, maxRetries)
.map(_ => action) ①②
}
```
① `_ => action` is a function that takes an integer and returns an `IO` value. We use underscore `_` to let the compiler know we don't need the int value, so we leave it unnamed.
② We map the list of integers with a function that changes each integer to the same `action` value. So, for `maxRetries = 3` we’d get the `List(action, action, action)` , which is a `List[IO[A]]` .
❺ | The last step is to somehow transform the list of IO values into a single IO value that will become the result of the retry function. Remember how we transformed a list of integers into one integer? We used foldLeft , which will work here as well! |
```
def retry[A](action: IO[A], maxRetries: Int): IO[A] = {
List.range(0, maxRetries)
.map(_ => action)
.foldLeft(action)((program, retryAction) => { ①
program.orElse(retryAction)
}) ②
}
```
① We fold the list of `IO` values by starting with `program = action` and then going through each element of the list (named `retryAction` ) and appending it to the program using `orElse` . We end up with a value that describes the program passed as `action` , which is retried using `orElse` a maximum of `maxRetries` times.
② Yay! It compiles now!
## Treating an unknown number of API calls as values
The third and final improvement we will make to the meeting scheduler is support for any number of attendees. The current version supports only one-on-one meetings between `person1` and `person2` :
```
def schedule(person1: String, person2: String,
lengthHours: Int): IO[Option[MeetingTime]]
```
Instead, we’d like to have a more generic and useful version:
```
def scheduledMeetings(attendees: List[String]): IO[List[MeetingTime]]
```
We can approach this problem with the same mindset we approach the `retry` function implementation.
❶ | We already have a list of names, so we can start with mapping each of those names to a program that fetches this particular attendee’s meetings. |
```
def scheduledMeetings(attendees: List[String]): IO[List[MeetingTime]] = {
attendees
.map(attendee => retry(calendarEntries(attendee), 10))
}
```
↑
We `map` each of the attendees to a `calendarEntries` call, which will be retried a maximum of 10 times. We end up with a `List[IO[List[MeetingTime]]]` , but the type of the returned value should be an `IO[List[MeetingTime]]` .

Again, note that this doesn't compile yet because types don't match. However, the compilation error is helpful because it pushes us in the right direction.
❷ | Since we have a list of IO s, we can use foldLeft again to fold this list into an IO value. This would be a little harder than with retry , because we’d need to use a flatMap inside the function passed to foldLeft . Generally, foldLeft is a very universal function, like map and flatMap , so it can be used in many different cases. However, we also have more specific functions that provide us with some folding logic out of the box. Here, we can use the new sequence function . |
```
def scheduledMeetings(attendees: List[String]): IO[List[MeetingTime]] = {
attendees
.map(attendee => retry(calendarEntries(attendee), 10))
.sequence
}
```
↑
We sequence a `List[IO[List[MeetingTime]]]` into an `IO[List[List[MeetingTime]]]` . What sequence does is fold all IOs from a given list into a single `IO` that holds a list of their resulting values. We say that the `List` of multiple `IO` s is sequenced into a single `IO` , which runs all IOs and returns their results in a single `List` .

❸ | We are very close to solving this function.We have a single IO that will call the API for each attendee and then return a list of results—one result per attendee. And since each result is another List , we end up with a List of List s. We don’t really need such a detailed result—we only need a list of all meetings for all attendees. That’s why it’s safe to just flatten the list of lists into a list of all elements from all lists. Remember that the list of lists is inside an IO —we still operate only on values describing side-effectful programs—so we need to flatten inside the second map call. |
```
def scheduledMeetings(attendees: List[String]): IO[List[MeetingTime]] = {
attendees
.map(attendee => retry(calendarEntries(attendee), 10))
.sequence
.map(_.flatten) ①
} ②
```
① Note that the first `map` operates on a `List` , while the second one operates on an `IO` returned by the sequence call.
② It compiles now!
Inside the second `map` call we have a function that takes a `List[List[MeetingTime]]` and returns a `List[MeetingTime]` . That means that after map we have `IO[List[MeetingTime]]` , which is exactly what the signature requires.

We now have the final version of the `scheduledMeetings` function, which we can use in the **final version** of the meeting scheduler that handles more than two attendees.
THIS IS BIG!
In FP, we “solve” a signature by providing the function body.
```
def schedule(attendees: List[String],
lengthHours: Int): IO[Option[MeetingTime]] = {
for {
existingMeetings <- scheduledMeetings(attendees)
possibleMeeting = possibleMeetings(
existingMeetings, 8, 16, lengthHours
).headOption
_ <- possibleMeeting match {
case Some(meeting) => createMeeting(attendees, meeting)
case None => IO.unit
}
} yield possibleMeeting
}
```
`sequence` , `traverse` , `flatTraverse` , and more!
The sequence function we’ve just met is just one of the possibilities to solve the problem of transforming a List of IO s into an IO of a List . The combination of map followed by sequence is so popular that there is another function that performs these two actions: traverse . Moreover, the combination of traversing followed by flattening is also a popular one; we use flatTraverse to do that. You can have a look at all scheduledMeetings implementations using foldLeft , traverse , and flatTraverse in the book’s source code . | |
`sequence` and other functions don’t work on `List` s of `IO` s only. They work on `List` s of other types we’ve met. For example, you can also `sequence` a `List` of `Option` s into an `Option` of a `List` !
## Practicing functional signature intuitions 
We’ve learned a lot of new functions in this chapter. Many of them are variations of functions we met in previous chapters, but there are a few new ones as well. Before we move on to tackle streams of infinite `IO` values, let’s see how well your _functional intuition_ works. **Your task is to fill in the blank implementations of the following 40 function signatures** . You will need to use only functions that we’ve met so far. Hint: All the missing implementations are one-liners!

Answers
```css
(1) x.map(f) (2) x.flatten (3) x.flatMap(f) (4) IO.pure(x) (5) IO.delay(impureAction())
(6) x.orElse(alternative) (7) x.sequence (8) x.sequence (9) x.appendedAll(y) or prependedAll
(10) x.filter(f) (11) x.foldLeft(zero)(f) (12) x.flatten (13) x.flatMap(f) (14) x.forall(f) or exists
(15) x.map(f) (16) x.filter(f) (17) x.foldLeft(zero)(f) (18) x.flatten (19) x.flatMap(f)
(20) x.forall(f) or exists (21) x.map(f) (22) x.filter(f) (23) x.foldLeft(zero)(f) (24) x.flatten
(25) x.flatMap(f) (26) x.forall(f) or exists (27) x.toIntOption (28) x.orElse(alternative)
(29) x.toRight(y) (30) x.toLeft(y) (31) x.sequence (32) x.map(f) (33) x.foldLeft(zero)(f)
(34) x.flatten (35) x.flatMap(f) (36) x.forall(f) or exists (37) x.orElse(alternative)
(38) x.toOption (39) x.sequence (40) x.sequence
```
## Summary
I hope you’ve enjoyed the ride and appreciate the versatility of pure functions operating on ( `IO` ) values. In this chapter we used a lot of things we had learned in previous chapters and took advantage of them to produce a real-world application that really does something that’s visible for an end user.
CODE: `CH08_*`
Explore this chapter’s source code by looking at `ch08_*` files in the book’s repository.
Use values to represent side-effectful programs
We learned that side-effectful programs can be described using the `IO` type. We learned that it has two constructors: `IO.delay` , which takes a block of code (a closure) that is lazily evaluated only when the `IO` value is executed, and `IO.pure` , which produces a value immediately (eagerly evaluated). This `IO` value will always succeed and return the given argument when executed.
Note that we only talked about synchronous programs. We will use many of these concepts when we write multi-threaded applications.
Use data from unsafe sources
We used this newfound power to call an external API that returns meetings for a given attendee. However, we learned that these kinds of calls are unsafe, meaning they may not behave exactly the same way each time they are called. One time they succeed, another time they fail with an exception. We learned that we can build values that describe recovery strategies like retries and fallbacks by using the `IO.orElse` function. We also noticed that intuition obtained using `Option` and `Either` helped a lot when working with `IO` .
We also discussed that retries and fallbacks may be relevant to the business logic, especially when we try to retry output actions.
Safely store data outside your program
We used the same approach to store data outside our program. The API that stores a meeting was called inside `IO.delay` , which delegated the responsibility of executing the side effect to its clients of our function. To do that, they need to call `unsafeRunSync()` in a different place of our codebase.
If functions don’t lie in their signatures, they become friendlier to developers; they are easier to test, maintain and refactor.
We also discussed that retries and fallbacks may be relevant to the business logic, especially when we try to retry output actions.
Indicate your code does side effects
The signatures of our functions indicate what they do. If a function returns a `List[MeetingTime]` , we know it doesn’t do any side effects because it’s just a pure function that returns a list. However, if a function returns an `IO[Option[MeetingTime]]` , we know it may execute some unsafe side-effectful, IO-heavy code when executed. It’s all in the signature!
Separate pure and impure code
Finally, we learned about the **functional core** concept. We bundle all pure functions together and delegate the impurity to the clients, so they can configure them to use specific IO actions (like console, HTTP, or APIs).
We also learned about essential and accidental concerns and that we should strive to put as many essential concerns as possible in the functional core.