In this chapter you will learn

  • how to declaratively design complicated program flows
  • how to use recursion and laziness to defer some decisions
  • how to handle IO-based streams of data
  • how to create and handle infinite stream of values
  • how to isolate time-dependent functionalities

“ Thinking is not the ability to manipulate language; it’s the ability to manipulate concepts. ”

—Leslie Lamport

To infinity and beyond

We have just learned how to read and write data using IO . In this chapter we will still use IO to represent our side-effectful programs as values, but our data will become much bigger—possibly infinite.

You have probably heard about data streams and streaming infrastructures. They have been very popular in recent years. The word streams , however, has become very overloaded and can mean different things to different people. Generally, streams were conceived to deal with incoming data that needs to be processed but doesn’t fit in the memory. However, we tend to use it in other cases, too—it has become a way to architect the control flow in many applications. Hence, it’s one of the possible software architecture choices and a very powerful one, too!

We will reuse a lot of knowledge about IO and its laziness. We will use sequence and orElse in this chapter, too! They really are ubiquitous in FP.

During the course of this chapter, we will show how functional programmers deal with streams of data in both use cases: as an architectural pattern and as a way to process big data. We will introduce the Stream type, which represents a description of streaming operations that, when executed, emit from zero to an infinite number of values . We will also put this Stream type in perspective of some of the existing stream-like solutions you may be familiar with, such as Java 8 streams, Java 9 reactive streams, functional reactive programming, or MapReduce systems .

We can also say that such a stream is unbounded. We will stick with using the infinity term in this chapter, though.

Dealing with an unknown number of values

We will try to rediscover the stream-based approach by implementing an online currency exchange that has the following requirements.

Requirements: Online currency exchange

  1. The user can request an exchange of a given amount of money from one currency to another currency.

  2. A requested exchange should be performed only when the exchange rate between the given pair of currencies is trending, which means that each of the last n rates is higher than the previous one—for example, 0.81, 0.82, 0.85 is a trend, while 0.81, 0.80, 0.85 is not (for n=3 ).

  3. We are given the API call function ( exchangeTable ) that fetches only the current exchange rates table from a given currency to all other supported currencies.

We will first try to implement the currency exchange using IO directly, recapping what we learned in the previous chapter. This won’t be an easy task because the second requirement is a tricky one. We will need to call the external API many times until we get a trend. Hence, the number of API calls that we need to make is initially unknown ! This is a new thing for us, but it’s pretty common in real-world cases. We will figure it out in this chapter.

Example

A user wants to exchange 1000 USD to EUR , but only when the USD-EUR rate is trending (i.e., the last three exchange rates from USD to EUR are increasing).

Dealing with external impure API calls (again)

To get current exchange rates for a currency of our choice, we will need to call an impure, external, side-effectful API. For demonstration purposes, we will use a simulated version, but as was the case in chapter 8, remember that in real-world applications this would have to be an HTTP client library that makes calls to a server that holds and updates current rates. Of course, all the caveats discussed earlier apply here as well. A call may randomly fail, take too long, or return some unexpected values.

Or it could be a different protocol, but this doesn’t matter until we get raw String s and numbers back. We don’t care about the internal communication protocol.

The implementation of this function is not important here, so please do not try to remember what it really does inside. The thing that we need to remember is its interface because this is something we are going to use throughout this chapter. So exchangeRatesTableApiCall takes a String , which is a name of the currency we want to exchange, and returns a Map of all available currencies we can exchange to. Each entry in this Map is a pair of String and BigDecimal —a name of a currency we can exchange to and the rate we can use to do it. Let’s see this in action.

We haven’t introduced a functional immutable Map yet, but we will do it very soon. For now, just assume that it works like a Java HashMap or a Python dictionary.

>

import ch09_CurrencyExchange.exchangeRatesTableApiCall  exchangeRatesTableApiCall("USD")
→ Map("JPY" -> 104.54, "EUR" -> 0.81)           ①
exchangeRatesTableApiCall("USD")
→ Exception in thread "main": Connection error  ②
exchangeRatesTableApiCall("USD")
→ Map(JPY -> 102.97, EUR -> 0.79)               ③

① We got a Map that contains two entries. It means we can exchange 1 USD for 104.54 JPY or for 0.81 EUR.

② Here, we got an exception, which is expected when we use impure code. Your REPL session might look different, and you may get way more connection errors (or none if you are lucky).

③ We got another Map back on our third call, with different rates!

Again, imagine that there is an external server that provides these exchange tables for us. We need to prepare for connection errors, other errors, dynamically changing rates, and even some unexpected missing rates (what if our third call returned a `Map` with only a JPY rate?). ## The functional approach to the design

We know what we need to do and what tools we have at our disposal. Since we are FP programmers now, there are two design choices that we may blindly assume from the get-go. First is that we will use a newtype (see chapter 7) to represent a currency, instead of using a raw String :

>

object model {    opaque type Currency = String
  object Currency {
    def apply(name: String): Currency = name
    extension (currency: Currency) def name: String = currency
  }
}
import model._
We could also introduce a special type, or even multiple types, to wrap the `BigDecimal` type, which represents both rates and money. Can you come up with some suggestions? Second is that the external data will be available as an input IO action—an `exchangeTable` function that returns an `IO` value: ``` def exchangeTable(from: Currency): IO[Map[Currency, BigDecimal]] ```

It should return a description of a program that does some side effects and returns a Map[Currency, BigDecimal] . It needs to use the exchangeRatesTableApiCall impure function internally, but it needs to be wrapped using a function we met in chapter 8. What was its name .

Answer:

IO.delay

![](/images/book/grokking-functional-programming/84c40c45-101f-49d8-9c53-92c64c043cc4.png) We now have the `Currency` model and a function that returns an `IO` . However, we can’t implement this `exchangeTable` function yet because the API call it uses internally returns a **`Map[String, BigDecimal]`** , not a **`Map[Currency, BigDecimal]`** . We need to learn some new stuff first! That’s why we haven’t shown its implementation yet. Calling `IO.delay` is not enough in this case! ## Immutable maps Let’s dig into immutable maps. In Scala, we usually use the `Map` type. Treat this section as a break from all the IO-based code that we will need to come back to very soon. Since our API is returning a map-like structure, we have a great opportunity to learn about immutable maps in practice. It should be pretty straightforward now because at this point you have a pretty good intuition about immutable data structures. You’ve seen lots of them already!                                                                 ![](/images/book/grokking-functional-programming/0a2caa55-94eb-4bbf-9f38-d6fd5b2e1f92.png) Q I thought this chapter would be about streams, not maps! A It is about streams! We will use the `Map` type not only to solve this chapter’s task (online currency exchange) but also as a foundation to learn about more advanced stream operations. Additionally, the `Map` type is ubiquitous in programming, so it’s a good idea to get acquainted. Stay tuned!

Map is an immutable type that contains key-value pairings (or mappings). It is parametrized using two types: one is the type of keys, and the second is the type of values. So a Map[Currency, BigDecimal] is a data structure that holds key-value mappings, where keys are Currency , and values are BigDecimal (we use BigDecimal because we work with money).

Map is immutable in Scala and other FP languages. Having immutable collections as a part of the standard library is one of the definitive FP language traits.

>

val noRates: Map[Currency, BigDecimal] = Map.empty  val usdRates: Map[Currency, BigDecimal] =
  Map(Currency("EUR") -> BigDecimal(0.82))  ①
val eurRates: Map[Currency, BigDecimal] = Map(
  Currency("USD") -> BigDecimal(1.22),      ②
  Currency("JPY") -> BigDecimal(126.34)     ③
)

① We use -> notation to represent a single key-value mapping. Note that we use => in functions.

② 1 EUR can be exchanged to 1.22 USD.

③ 1 EUR can be exchanged to 126.34 JPY.

Obviously, just like with `List` s and `Set` s, when you **add** a new key-value pair to a `Map` , you create a new `Map` value, leaving the original untouched.

>

val updatedUsdRates = usdRates.updated(Currency("JPY"), BigDecimal(103.91))  usdRates                       ①
→ Map(Currency(EUR) -> 0.82)
updatedUsdRates                ②
→ Map(Currency(EUR) -> 0.82, Currency(JPY) -> 103.91)

① usdRates hasn’t changed. It’s still the same as above when we created it.

② updatedUsdRates is a new Map value that holds two key-value pairs.

Note that we append something to a `List` using `appended` , and we update mappings in a `Map` using `updated` . Intuitively, to **remove** a mapping under a key, we use `removed` , and to **get** a value stored under a specific `key` , we use `get` . And that’s all! That’s how learning a new immutable data structure looks when you already have experience with other ones. Think for a minute about the type `Map.get` returns. What if we want to get a value from a nonexisting key? ## Practicing immutable maps ![](/images/book/grokking-functional-programming/3f5cf784-59d6-46a6-8cdf-0a039204ac9b.png) When learning a new immutable data structure, it’s best to give a quick intro and then go straight into coding. We’ve just gone through some `Map` operations, and now it’s time to write some code and learn the remaining ones. **Your first six tasks are to create the following values** (replace `???` with actual code that will produce the described values):

>

val m1: Map[String, String] = ???  m1
→ Map("key" -> "value")

1

A map that contains a single pair: “key" -> “value"

>

val m2: Map[String, String] = ???
m2
→ Map("key" -> "value", "key2" -> "value2")

2

A map that updates m1 and stores “value2" under “key2"

>

val m3: Map[String, String] = ???
m3
→ Map("key" -> "value", "key2" -> "another2")

3

A map that updates m2 and stores “another2" under “key2"

>

val m4: Map[String, String] = ???
m4
→ Map("key2" -> "another2")

4

A map that updates m2 and removes the “key"

>

val valueFromM3: Option[String] = ???
valueFromM3
→ Some("value")

5

A String value stored under “key" in m3

>

val valueFromM4: Option[String] = ???
valueFromM4
→ None

6

A String value stored under “key" in m4 (which doesn’t have this key)

**The last task is to write down the results of the five expressions below** :

>

val usdRates = Map(Currency("EUR") -> BigDecimal(0.82))  usdRates.updated(Currency("EUR"), BigDecimal(0.83))
usdRates.removed(Currency("EUR"))
usdRates.removed(Currency("JPY"))
usdRates.get(Currency("EUR"))
usdRates.get(Currency("JPY"))

7

Five values created from the original usdRates map

Answers ```javascript 1. val m1: Map[String, String] = Map("key" -> "value") 2. val m2: Map[String, String] = m1.updated("key2", "value2") 3. val m3: Map[String, String] = m2.updated("key2", "another2") 4. val m4: Map[String, String] = m3.removed("key") 5. val valueFromM3: Option[String] = m3.get("key") 6. val valueFromM4: Option[String] = m4.get("key") 7a. Map(Currency(EUR) -> 0.83) 7b. Map.empty 7c. Map(Currency(EUR) -> 0.82) 7d. Some(BigDecimal(0.82)) 7e. None ``` Notice that `Map.get` returns an `Option` . This should not come as a surprise. The consistency of functional programming APIs is much higher than imperative ones. That’s why knowing the `Option` type may be enough to guess what `Map.get` returns. It returns an `Option` because a value under any given key may or may not be in the map. ## How many IO calls should we make? Now that we know how `Map` works, we can go back to our example. All we have at our disposal is the function that makes an unsafe API call for a currency and returns a `Map` back. What should our next step be? We will go back to the problem of wrapping this API call in an IO-based function soon. Let’s think about the task description in more detail. Remember that a single API request provides a single exchange rate. This introduces a big problem when we think in terms of one of the requirements.                                                                 ![](/images/book/grokking-functional-programming/0e7c5586-1eff-49b5-9d8d-e48feb551a17.png) A requested exchange should be performed only when the exchange rate between the given pair of currencies is trending, which means that each of the last `n` rates is higher than the previous one—for example, `0.81, 0.82, 0.85` is a trend, while `0.81, 0.80, 0.85` is not (for `n=3` ). Let's assume `n=3` for now to simplify the thinking process. The requirement says that we need to make decisions based on several currency rates. However, we don’t know whether a trend will happen after the first three API calls, or we’ll need to make a hundred of them. **It’s also possible that we’ll never find a trend at all!** In other words, we may imagine that, in some circumstances, we may need to wait for a long time until a currency rate changes in our favor. We need to be prepared to make a very large, **possibly infinite** , number of IO calls. Top-down vs. bottom-up design We don’t really know how to approach this problem. So far, we’ve been making a fixed number of IO calls, and it has worked fine. Here, we’ll need something more. We can approach such a problem in two ways. The first is to start at the _top_ of our program, and the second is to start from the _bottom_ . FP allows us to use either approach. Up until now we prioritized the top-down approach. We usually started with a signature of a highest-level function that would be used by our clients and then worked our way down, implementing smaller and smaller functions. If we chose this approach again, we’d need to start with ```sql def exchangeIfTrending(amount: BigDecimal, from: Currency, to: Currency): IO[BigDecimal]① ``` ① This function returns a description of a program, which, when executed successfully, continuously checks exchange rates from the “from” currency to the “to” currency, and if they are trending, it exchanges the amount using the last rate. It doesn’t finish successfully (or at all) otherwise. In fact, the signature above is exactly what we’ll end up with at the end of this chapter. However, right now there are too many unresolved problems related to a possibly infinite number IO calls. We just wouldn’t know where to start. Thus, **we’ll use the bottom-up approach instead** . ## The bottom-up design Even though the top-down approach is usually better—it enables us to focus on our client needs instead of technical obstacles—there are some cases in which we can’t use it. Then, we need to fall back to using the bottom-up design, meaning we start solving smaller and easier problems first and build our way up to getting a fully working solution. This will also allow us to catch some breath before we tackle the difficult problem of a potentially infinite number of IO calls. Let’s use the bottom-up design. What are the **small problems** that need to be solved and we can tackle right away? As you can see, the top-down approach is about starting with a signature and implementing it. The bottom-up approach is looking for small problems and starting with them.

1

Checking if rates are trending

We know we need a function that decides whether a given sequence of rates is trending or not. That means we need a function with the following signature:

``` def trending(rates: List[BigDecimal]): Boolean ``` Here are some calls that explain how `trending` should work: ``` trending(List.empty) → false trending(List(BigDecimal(1), BigDecimal(2), BigDecimal(3), BigDecimal(8))) → true trending(List(BigDecimal(1), BigDecimal(4), BigDecimal(3), BigDecimal(8))) → false ```

2

Extracting a single currency from a table

We know that we’ll need to deal with exchange tables for a single given currency—represented by a Map[Currency, BigDecimal] . When we make three successful API calls, we’ll have three maps. For example:

``` val usdExchangeTables = List( Map(Currency("EUR") -> BigDecimal(0.88)), Map(Currency("EUR") -> BigDecimal(0.89), Currency("JPY") -> BigDecimal(114.62)), Map(Currency("JPY") -> BigDecimal(114)) ) ``` We will have a list of multiple maps at hand, but we will only need a single exchange rate from each of them. In this case we need to extract the `EUR` rate from each map. Hence, a function called `extractSingleCurrencyRate` will come in handy: ``` usdExchangeTables.map(extractSingleCurrencyRate(Currency("EUR"))) ① → List(Some(BigDecimal(0.88)), Some(BigDecimal(0.89)), None) ``` ① This function will need to return an `Option` because we can’t be sure that all maps include a given currency. What would the result be if we used `JPY` instead? ## Advanced list operations We identified two small functionalities that we will most likely need in the final solution. We do not care about connections between them yet. We will just implement them in isolation and then look for the next challenges, going _up_ in the solution blueprint. Hence the “bottom-up" name. Let’s implement the `trending` function first. We will do it by introducing two new `List` functions, **`drop`** and **`zip`** , and a related new type: **the tuple** . Both _dropping_ and _zipping_ can be used for many collection types you already know, and we will use them in streams later in the chapter. Nevertheless, these are pretty powerful and worth having in your functional programmer toolbox (alongside all the others we have already met in this book—dozens of them, so far). A naive trending implementation, assuming that the list always contains three elements may look like this: ``` def naiveTrending(rates: List[BigDecimal]): Boolean = { ① rates(0) < rates(1) && rates(1) < rates(2) ① } ① ``` ① It’s usually a bad sign when you implement a function that relies too much on a given list size and specific indices. If you don’t like this solution, welcome to the club. **It’s a very bad solution!** We can’t assume that any given list will always contain three elements. So the function above is not a pure function. It doesn’t return a `Boolean` for all possible `List` s. It will fail for lists smaller than three elements and will not produce correct results for larger lists. We need something different, something better and more bulletproof—a real, pure function. Let’s try implementing `trending` step by step:

❶

Traditionally, let’s start with the signature and try to think about what should happen when a given list is small:

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && ... } ``` ① If the list is empty or contains just a single element, there is no way that it forms a trend, so return `false` .

❷

Usually, when we want to get a Boolean based on a condition applied to all elements of a list, we need to use forall . Will it work here? Let’s try:

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && rates.forall(rate => rate > ???) ① } ``` ① **This won’t work** , because we need to somehow check whether each element is larger than the _previous one_ in the list, so the function we pass to `forall` needs access to the current and the previous element at once to make an informed decision. ## Introducing tuples Is there a way out of this? Could we use the elegant `forall` function and still be able to safely implement the `trending` function without worrying about list indices and sizes? Yes, but we’ll need a _tuple_ ! Before we introduce it properly, let’s talk about our use case. We failed to implement the `trending` function because a single element of the input list contained only a single rate. We could have used `foldLeft` to solve that, but there is another solution that may be a better fit. We need to make sure **a single element in the list contains all the information we need to make a decision** . In our case, a given list forms a trend if each rate is larger than the previous one. So for each rate, we also need access to the previous one. **We need a list of pairs** . Did you try to implement the `trending` function using `foldLeft` ? `foldLeft` is a versatile tool, and you will find yourself reaching for it on many occasions. It’s good to practice using it whenever you can.

>

val rates = List(BigDecimal(0.81), BigDecimal(0.82), BigDecimal(0.83)) ①  val ratePairs: List[(BigDecimal, BigDecimal)] = List(                  ②
  (BigDecimal(0.81), BigDecimal(0.82)),
  (BigDecimal(0.82), BigDecimal(0.83))
)

① Given a sequence of three rates ...

② ... we’d like to be able to convert it to this list of two pairs.

Note that to define a tuple we use an additional set of braces: `(a, b)` . Tuples `(A, B)` is a two-tuple—a product type that consists of two values: the first is of type `A` , and the second is of type `B` . For example, `(String, Int)` is a tuple, `(String, Boolean)` is a tuple, and even `(String, List[String])` is a tuple. Generally, the tuple is an implementation of the product type, just like the `case class` —the only difference is that tuples don’t have names, and the values they hold are not named as well. We also can use tuples with the same type (i.e., `(A, A)` ). For example `(BigDecimal, BigDecimal)` is a tuple of two `BigDecimals` . `(BigDecimal(0.81), BigDecimal(0.82))` is a value of this type. `List[(BigDecimal, BigDecimal)]` is a list of tuples. There are also tuples that can hold a different number of values: for example, (A, B, C) is a three-tuple (triplet). `(String, Int, Boolean)` is one of its possible types. One of its possible values is `("a", 6, true)` . In this chapter, we’ll use two-tuples only, sometimes called pairs or just tuples. So `ratePairs` above is a list of tuples. Each tuple in this list consists of two values, each of the `BigDecimal` type. They are unnamed, but we will use the mechanism we learned about in chapter 7 to **destructure them into individual values** . They are product types after all, so we could achieve exactly the same result by creating a named tuple instead: Remember which mechanism that was? If not, we’ll refresh you very soon.

>

case class RatePair(previousRate: BigDecimal, rate: BigDecimal) ①

① This is analogical to a tuple (BigDecimal, BigDecimal) .

Both of the following can more or less do the same job: ``` val tuple: (BigDecimal, BigDecimal) = (BigDecimal(2), BigDecimal(1)) val caseClass: RatePair = RatePair(BigDecimal(2), BigDecimal(1)) ``` However, they carry a different amount of information! ## Zipping and dropping We can create a list of tuples by **zipping** two lists together. For example:

>

val ints: List[Int]       = List(1, 2, 3)  val strings: List[String] = List("a", "b", "c") ①
ints.zip(strings)
→ List((1, "a"), (2, "b"), (3, "c"))           ②

① Given two List s: a list of Int s and a list of String s ...

② ... using zip we can create a single list of (Int, String) tuples that contain corresponding elements from both lists.

In our case we could **`zip`** `rates` with itself:

>

val rates = List(BigDecimal(0.81), BigDecimal(0.82), BigDecimal(0.83))   rates.zip(rates)
→ List(
  (BigDecimal(0.81), BigDecimal(0.81)), 
  (BigDecimal(0.82), BigDecimal(0.82)), 
  (BigDecimal(0.83), BigDecimal(0.83))
)
But it’s not exactly what we wanted. Here we just zipped two identical lists with each other. It’s good to know that it’s possible, and useful in some cases. This one is not one of them, though. We want to have a list of `(BigDecimal, BigDecimal)` tuples that contain the previous and the current rate. We need to **`drop`** the first element of the second list to be able to have pairs of neighboring rates. `rates.drop(1)` returns a new list with one element less than the original `rates` list. Practically, it drops `n` elements from the beginning of the list. `dropRight` , on the other hand, drops from the end. ![](/images/book/grokking-functional-programming/2b8bd0b5-f61b-42a6-8cdd-86fb7a8c222a.png)

>

rates  → List(BigDecimal(0.81), BigDecimal(0.82), BigDecimal(0.83))
rates.drop(1)
→ List(BigDecimal(0.82), BigDecimal(0.83))
rates.zip(rates.drop(1)) 
→ List(
  (BigDecimal(0.81), BigDecimal(0.82)),
  (BigDecimal(0.82), BigDecimal(0.83))
)
![](/images/book/grokking-functional-programming/c75eab8e-7d1b-4730-989b-dc3a5b8f5fae.png) There are also alternatives like `zipWithNext` and `zipWithPrevious` that we could use here. When we `zip` a three-element list with a two-element list, we get a new two-element list back because only two tuples can be safely created (the third element of the bigger list is ignored). There are more versions of the `zip` function in different libraries and APIs that cover more zipping outcomes (just like there are several versions of joins in relational databases). We will learn one more version later, when we will need to `zip` two infinite streams of values. But first, let’s implement `trending` . ## Pattern matching on tuples Let’s go back to implementing `trending` . We tried to use `forall` as the most natural way of checking if a condition holds for all elements in a list. We now have more tools in our inventory: `drop` and `zip` . Let’s try again. Note we are in the bottom-up design mode. We start with small functions and then use them in `IO` -based ones.

❶

Traditionally, we start with the signature and try to think about what should happen when a given list is small:

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && ... } ```                   ↑ If the list is empty or contains just a single element, there is no way that it forms a trend, so return `false` .

❷

Usually, when we want to get a Boolean based on a condition applied to all elements of a list, we need to use forall . Will it work here? Let’s try:

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && rates.forall(rate => rate > ???) } ```                   ↑ **This won’t work** , because we need to somehow check whether each element is larger than the _previous one_ in the list, so the function we pass to `forall` needs access to the current and the previous element at once to make an informed decision. This is where we left off before meeting zip and drop. This is where we left off before meeting `zip` and `drop` .

❸

Now we know what to do to implement trending using forall . We need to operate on a different list—one that holds tuples of BigDecimals: (previousRate, rate) .

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && rates.zip(rates.drop(1)) } ```                   ↑ We `zip` the `rates` list with the same list that doesn’t have the first element. This way, the first rate is zipped with the second rate, the second is zipped with the third, and so on. This way we get a list of tuples, each of them having both a previous rate and rate.

❹

Finally, we can use forall , which returns true if all the elements in the list return true when applied to the function we pass as an argument. We can access and easily name both values in the tuple by destructuring it using a familiar pattern-matching mechanism.

``` def trending(rates: List[BigDecimal]): Boolean = { rates.size > 1 && rates.zip(rates.drop(1)) .forall(ratePair => ratePair match { case (previousRate, rate) => rate > previousRate ① }) } ``` ① Note how naming both values in the tuple improves readability. `ratePair` is a tuple. A tuple represents a product type, just like the `case class` we have been using so far. We can destructure a tuple using the `matchcase` syntax. This is a tuple of two values, so we name both values in the tuple and return `true` if the second value is bigger than the first one. **That’s it!** We coded the pure `trending` function that supports all list sizes. ## Coffee break: Working with maps and tuples ![](/images/book/grokking-functional-programming/073fdaa1-e0cc-4e05-9aa6-337ed6feef8d.png) Now, it’s your turn to play around with maps and tuples. **Your task is to implement the second small function in our bottom-up design journey** . Afterwards, we will have all the information and implementations to finally start working with infinite IO-based streams of values. Here’s the signature of the function you need to implement: Note that we don’t have any special exercise for the `drop` and `zip` functions. At this point you should be able to learn new pure functions in a breeze. If any of them cause problems, the chapter’s source code in the book repository is your friend. ``` def extractSingleCurrencyRate(currencyToExtract: Currency) (table: Map[Currency, BigDecimal]): Option[BigDecimal] ``` This is a curried function—it has two lists of parameters. It’s a pretty common choice in FP when you plan to use a function with `map` . Here’s how we imagine it may be used: ``` val usdExchangeTables = List( Map(Currency("EUR") -> BigDecimal(0.88)), Map(Currency("EUR") -> BigDecimal(0.89), Currency("JPY") -> BigDecimal(114.62)), ① Map(Currency("JPY") -> BigDecimal(114)) ) usdExchangeTables.map(extractSingleCurrencyRate(Currency("EUR"))) → List(Some(BigDecimal(0.88)), Some(BigDecimal(0.89)), None) ``` ① Here are few exchange tables for `USD` . You may interpret this as a list of three API call results. Note that one of the results doesn’t contain an exchange rate to `EUR` . Note how we pass a function from a `Map` to `Option[BigDecimal]` . This function is created by calling `extractSingleCurrencyRate(Currency("EUR"))` —note that only the first parameter list was used. This approach heavily improves readability; we `map` all the `USD` exchange tables we got (represented as `Map` s) with a function that extracts a rate to `EUR` from a given exchange table. Your implementation needs to use both parameters: the map representing an exchange table ( `table` ) and the currency we want to extract ( `currencyToExtract` ). If a given currency rate is present in the exchange table, return it as `Some` . Otherwise, return `None` . Additionally, note how using the ubiquitous `map` function helped us frame the problem differently: instead of extracting an `EUR` rate from all exchange tables, we can focus on a single exchange table. Please make sure your implementation satisfies the use case defined above before proceeding. It’d be a good idea to come up with some additional tests, too. What if we want to extract yen ( `JPY` )? Or `BTC` ? The use case presented above is like a test: you need to call a function with an input and expect a specific output. Hints 1. All functions you know from **`List`** s, like **`map`** or **`filter`** , work on **`Map`** s too. However, remember they operate on key-value tuples. 2. **`Map`** has a **`values`** function that returns an **`Iterable`** , which has many functions similar to **`List`** , including **`headOption`** . ## Coffee break explained: Working with maps and tuples ![](/images/book/grokking-functional-programming/073fdaa1-e0cc-4e05-9aa6-337ed6feef8d.png) The function can be solved in multiple different ways, but there is one way that is the most reasonable. If you got it, congratulations! However, if you did it differently, don’t worry. Generally, if you tested your implementation against the test cases proposed in the task description, you can be pretty sure that your solution is correct. Here, we will show two possible approaches to solving this exercise. One of them uses `filter` and treats the `Map` as a list of tuples, while the second uses `Map.get` directly. The latter is superior, because the **function we asked to implement is in fact** `Map.get` **in disguise** . No matter which version is closer to your implementation, make sure you understand why these implementations are doing the same thing. A situation when you first define a signature and then it turns out there is already a function that does exactly what you need is pretty common in FP. Version 1 This is worse than the second one, but it shows how to do operations on tuples using pattern matching.

>

def extractSingleCurrencyRate(currencyToExtract: Currency)     ①          (table: Map[Currency, BigDecimal]): Option[BigDecimal] = {
  table
    .filter(kv =>                                              ②
      kv match {
        case (currency, rate) => currency == currencyToExtract
      }
    )
    .values                                                    ③
    .headOption                                                ③
}

① Scala allows us to write this function in a more concise way, but we use only the basic syntax in this book. See Appendix A for details.

② Map has the filter function defined as well. filter gets a tuple and needs to return a Boolean value that indicates whether this particular entry should be filtered. The function we pass to filter uses the pattern-matching syntax to destructure a tuple into two named values.

③ After calling filter we get a Map back that contains only filtered entries. Then, we call the values function that returns a list of values , in our case BigDecimals . We know that there will be a maximum of one entry (we filtered a single key), so we call headOption to get the first (and only) element of this list wrapped in Some , or None if it’s empty.

Version 2 Did you notice that we asked you to implement Map.get?

>

def extractSingleCurrencyRate(currencyToExtract: Currency)          (table: Map[Currency, BigDecimal]): Option[BigDecimal] = {
  table.get(currencyToExtract) ①②
}

① We first defined a function that we need and then it turned out that a simple Map.get call implements it. We can now get rid of this function and use Map.get directly or we can leave the function as is because it explains more in terms of domain language.

② Map.get gets a key and returns an Option . If the provided key has a corresponding value inside the map, this value (wrapped in Some ) is returned. Otherwise, None is returned.

## Functional jigsaw puzzle We just implemented two new functions based only on requirements. ``` def trending(rates: List[BigDecimal]): Boolean def extractSingleCurrencyRate(currencyToExtract: Currency)(table: Map[Currency, BigDecimal]): Option[BigDecimal] ``` We also learned everything to finally wrap our impure API call in `IO` .

>

def exchangeTable(from: Currency): IO[Map[Currency, BigDecimal]] = {    IO.delay(exchangeRatesTableApiCall(from.name)).map(table =>
    table.map(kv =>
      kv match {
        case (currencyName, rate) => (Currency(currencyName), rate)
      }
    )
  )
}

① An API call returns a Map[String, BigDecimal] , so on top of wrapping it in IO.delay, we also need to transform its potential result using IO.map. We pass a function that transforms a Map[String, BigDecimal] into our domain model–based Map[Currency, BigDecimal] using pattern matching on Map s.

Since we are building bottom-up, we need to make a decision now:

  1. Are these functions enough to start building something bigger?

  2. Are we still missing another independent small function?

In this case we have all we need, so we can continue with #1. So how exactly can we use these three functions?

Working with small functions means you need to look at their signatures and find out which functions’ inputs are compatible with others’ outputs. It’s like solving a jigsaw puzzle— only some pieces fit together. Let’s take a look.

`extractSingleCurrencyRate` takes a `Map[Currency, BigDecimal]` , and `exchangeTable` returns a `Map[Currency, BigDecimal]` , wrapped in `IO` . Thus, we can fit these pieces together using a `map` call: ``` exchangeTable(Currency("USD")).map(extractSingleCurrencyRate(Currency("EUR"))) ``` Similarly, we see that the `trending` function takes a `List[BigDecimal]` , while we only have an `Option[BigDecimal]` on our hands (returned from `extractSingleCurrencyRate` ). We also know that `trending` will need lists of multiple elements to be able to detect a trend at all. Thus, we need to fetch more `BigDecimal` -typed exchange rates before calling `trending` . For simplicity, let’s assume we only want to detect trends of size three (for now):

>

for {     table1 <- exchangeTable(from)                            ①
  table2 <- exchangeTable(from)                            ①
  table3 <- exchangeTable(from)                            ①
  lastTables = List(table1, table2, table3)
} yield lastTables.flatMap(extractSingleCurrencyRate(to))  ②

① from and to are Currencies . We are looking for a trend in rates between from and to .

② Note that this flatMap works on a List and flattens internal Option s by implicitly treating them as List s of 0 or 1 element.

It turns out that this is an implementation of a very useful function! ## Following types in a bottom-up design Just by following types and analyzing the requirements, we ended up with a function that returns a description of a program, which, when executed successfully, will return a `List` of up to three last exchange rates of currencies: `from` and `to` . We will name this function `lastRates` . Remember that API calls and many other side-effectful functions are not safe, so we need to implement some recovery strategies. Here, we’ll reuse the `retry` function from chapter 8 (with `maxRetries = 10` ).

>

import ch08_SchedulingMeetings.retry  def lastRates(from: Currency, to: Currency): IO[List[BigDecimal]] = {
  for {
    table1     <- retry(exchangeTable(from), 10)
    table2     <- retry(exchangeTable(from), 10)
    table3     <- retry(exchangeTable(from), 10)
    lastTables = List(table1, table2, table3)
  } yield lastTables.flatMap(extractSingleCurrencyRate(to))
}
Note that generators in the for comprehension are `flatMap` ping `IO` s, while `flatMap` in the yield expression works on a `List` . Our newly discovered `lastRates` function takes a currency we’d like to convert `from` and the currency we’d like to convert `to` , and it returns a description of a program that, when executed, will return a list of exchange rates between these currencies. And that’s exactly the `List[BigDecimal]` we need for `trending` ! That all means we can finally take the last step up and implement the last high-level function that exchanges money if rates are trending. `trending` A function that takes a `List[BigDecimal]` and returns a `Boolean` ; it is true if the given `rates` list contains a trend.

>

def exchangeIfTrending(    amount: BigDecimal, from: Currency, to: Currency
): IO[Option[BigDecimal]] = {
  lastRates(from, to).map(rates =>
    if (trending(rates)) Some(amount * rates.last) else None
  )
}
We are returning the amount that can be exchanged using a rate, which is trending. In the real world, we’d probably need to persist it using an additional output action. **We are done!** `exchangeIfTrending` implements this chapter’s requirements. We have a function that describes a program that will check last rates and exchange the given amount using the most recent rate, but only if the rates between the given currency pair have been _trending_ . If not, it will return `None` . Obviously, you could plug in another IO value that describes an output action, which stores the resulting exchanged amount somewhere, transactionally. However, for simplicity, we’ll skip this part and focus on other aspects instead. After calling `exchangeIfTrending` , we could call `flatMap` and pass some other function that describes a program that stores the resulting exchange transaction externally. ## Prototyping and dead ends The functional jigsaw puzzle we just solved was not a particularly demanding one, but I hope it has shown that the bottom-up design is a perfectly fine approach, especially when working with pure functions and their signatures. We started small and have been _pushing upward_ and learning quite a bit about a possible solution space and requirements along the way. **We have been prototyping** . However, let’s remember that we made some critical assumptions, such as fixing the number of rates that are taken into consideration in trend computation (we only take three for now). Some details were hardcoded and allowed us to focus on more important, higher-level aspects. However, the time has come to revisit them and decide whether this particular prototype is worth expanding into the final product. It must be highlighted that most of the time **prototypes turn out to be dead ends** . And this is, unfortunately, true in our case as well. Let’s recall the main requirement we were tasked to implement:                                                                 ![](/images/book/grokking-functional-programming/0e7c5586-1eff-49b5-9d8d-e48feb551a17.png) A requested exchange should be performed only when the exchange rate between the given pair of currencies is trending, which means that each of the last `n` rates is higher than the previous one—for example, `0.81, 0.82, 0.85` is a trend, while `0.81, 0.80, 0.85` is not (for `n=3` ). There are several very important unknowns in our current prototype that disqualify it from being the final solution. Right now our prototype tries only the first three rates, checks whether they are trending, and exchanges a given amount if they are trending (which we signal by returning a `Some` that contains an amount of exchanged money in the new currency). However, if the first three rates are not trending, our function returns `None` and calls it a day. We want something more useful: an app (a function) that will wait for a trend to happen and only then conclude with a successful exchange. In other words, the problem with the current implementation is that we fetch three rates and make a single decision. Instead, we’d like to fetch potentially thousands of rates and only make a decision when we stumble upon a trending sequence. Additionally, we’d like to be able to configure our function to use arbitrary sizes of trending sequences. We’ve used `n=3` so far, but `n=20` should definitely be possible as well without any additional hassle. How can we do this? We need to enter the world of possibly infinite IO calls we mentioned earlier in the chapter. The first version of `exchangeIfTrending` function uses only the concepts we’ve learned previously. ## Recursive functions Step 2 **Using `IO` with recursio** . The problem we are facing right now is a very common one. We want to make multiple calls to an external API, but we don’t know how many will suffice because it depends on the values this API produces—which we’ll know only in the future! In other words, we’d like to be able to call `exchangeIfTrending` until it returns a `Some` . Hence: ``` lastRates(from, to).map(rates => if (trending(rates)) Some(amount * rates.last) else None ① ) ``` ① If we end up in this case, we know that we don’t have a trend, so we’d like to try again instead of returning `None` . This is a job for **recursion** . We talk about recursion when something is defined in terms of itself. We will talk about **recursive functions** and **recursive values** . Let’s start with recursive functions. A function is recursive if it’s used inside its own implementation (i.e., it’s defined, at least partially, in terms of itself). If this sounds cryptic, let’s try to apply this to our example. In our case we’d like `exchangeIfTrending` to try again in case no trend was found for the first three API calls. And how can we try again? By providing exactly the same program—that is, calling `changeIfTrending` internally! THIS IS BIG! In FP, we solve a lot of problems using recursion.

>

def exchangeIfTrending(    amount: BigDecimal, from: Currency, to: Currency
): IO[Option[BigDecimal]] = {
  lastRates(from, to).map(rates =>
    if (trending(rates)) Some(amount * rates.last) 
    else exchangeIfTrending(amount, from, to) ①
  )                                           ②
}

① We replaced the None with a call to the function we are defining. However, the compiler complains that exchangeIfTrending returns an IO in the else clause, while it expected an Option (previously, we had None there, and remember that the if–else expression needs to provide a value of the same type in both cases.).

② Compilation error!

That means we need a flatMap (on IO ) or a for comprehension. Additionally, we can’t get rid of the IO from the signature, which makes us promote ( lift ) the if clause expression into an IO value and move it into the for comprehension (it’s going to be flatMap ped now, not map ped):

Remember how flatMap / map can be rewritten to a for comprehension like we did in chapter 5?

>

def exchangeIfTrending(    amount: BigDecimal, from: Currency, to: Currency
): IO[Option[BigDecimal]] = {                             ①
  for {
    rates  <- lastRates(from, to)
    result <- if (trending(rates)) IO.pure(Some(amount * rates.last)) 
              else exchangeIfTrending(amount, from, to)   ②
  } yield result
}

① Both clauses are IO now; the compiler is happy.

② Here is the recursive function call.

The result is an `Option[BigDecimal]` , and because it’s yielded from a for comprehension that works on `IO` values, the signature of the whole function is maintained. It’s `IO[Option[BigDecimal]]` . **We have just defined a recursive function** . ## Infinity and laziness When you look closely at our recursive function, you will notice that if we never get rates that are trending, the function describes a program that will end up calling itself again and again without returning. So it’s possible that when we `unsafeRunSync` , the `IO` value returned by this function, our application will keep working infinitely. Remember that we use `unsafeRunSync` to execute the program described by the given `IO` value. It’s done outside of the functional core of the application. But again, since we are working with `IO` , this potentially infinite execution won’t happen after calling the `exchangeIfTrending` function. The function call will just return an `IO` value that describes a program that may not finish at all, depending on external world values—in this case, exchange rates returned by API calls. So even though we described a possibly infinite program, we are on the safe side, while we keep working with `IO` values. This is possible because, as discussed previously, `IO` takes advantage of laziness (lazy evaluation). The code we pass to `IO.delay` is not executed, it’s just saved for later execution.

If it sounds simple and repetitive to you, consider another example. We implemented the recursive function by calling itself inside the flatMap call and making use of its internal laziness. However, had we used recursion to directly create the value itself, without making any lazy calls, we won’t get any value back . For example, calling the following function crashes or freezes the program:

``` def exchangeCrash( amount: BigDecimal, from: Currency, to: Currency ): IO[Option[BigDecimal]] = { exchangeCrash(amount, from, to) } exchangeCrash(BigDecimal(100), Currency("USD"), Currency("EUR")) → Exception in thread "main" java.lang.StackOverflowError ① ``` ① Note that we didn’t even call `unsafeRunSync` . This failed before even returning an `IO` value! As you can see, we need to be very careful when using recursion. It worked fine when we used `flatMap` , but it didn’t work when it called itself directly. Additionally, did you notice that when you defined `exchangeCrash` , the compiler warned you? But we can still create a function that returns a program which, when executed, will never stop—it will go infinitely, unconditionally.

>

def exchangeInfinitely(    amount: BigDecimal, from: Currency, to: Currency
): IO[Option[BigDecimal]] = {
  for {
    rates  <- lastRates(from, to)
    result <- exchangeInfinitely(amount, from, to)                    ①
  } yield result
}
exchangeInfinitely(BigDecimal(100), Currency("USD"), Currency("EUR")) ①
→ IO                                                                 ②

① We use IO.flatMap . The recursive call will not happen until we get rates some time in the future. Note that we don’t even use the rates value anywhere. Nevertheless, it will work fine—that is, it will not crash and return an IO value.

② We properly got an IO value, which describes a program that will never finish. Note that we did not call unsafeRunSync again. We used the power of lazy evaluation to create an infinite program.

## Recursive function structure We were able to use `flatMap` and its lazy evaluation to create a recursive function that returns an `IO` value describing a potentially infinite program. There are, of course, more caveats and details—we are just scratching the surface here—but this insight alone should allow us to go very far. Remember that with great power comes great responsibility. Let’s learn about these caveats first and then move on to functional streams, which use all these recursion techniques underneath but hide many details, so we can focus on solving business problems. **Infinity, laziness, and recursion go hand in hand** in a lot of functional programs. This popular combination allows us to use descriptive expressions instead of imperative recipes. We established that recursion is very important for functional programmers. However, building a proper recursive function may not be an easy task, especially when we start working with possibly infinite executions. The most important thing to remember is that we need to have a **base case** (i.e., a place in the function where it doesn’t call itself). This will be the exit point of a recursive function call. This is the place that allows us to at least believe that it may be executed and return a result. Without a base case all bets are off. In our recursive function the base case is when we confirm that given `rates` are `trending` and the whole function returns an `Option[BigDecimal]` . THIS IS BIG! Lazy evaluation, recursion, and potential infinite executions have a lot in common. ``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[Option[BigDecimal]] = { for { rates <- lastRates(from, to) ① result <- if (trending(rates)) IO.pure(Some(amount * rates.last)) else exchangeIfTrending(amount, from, to) } yield result } ``` ① The recursion base case is here. When this `if` returns `true` , we don’t recursively call the function itself. We return the eagerly evaluated value wrapped in `IO` . Again, this function returns an `IO` , which, when executed, will return an `Option[BigDecimal]` , fail, or never finish. We discussed failure handling earlier and all of these techniques still apply whenever you work with unsafe side-effectful code. Let’s put failures aside for now and focus on the difference between getting a successful value and getting no result at all (meaning that the program, when executed, never finishes).

Quick question : Look closer at the function above. It returns an IO of Option . Is it possible that executing this program returns None ? How?

The answer is on the next page (it’s “no").

## Dealing with an absence in the future (using recursion) The `exchangeIfTrending` function claims that it returns an `IO[Option[BigDecimal]]` . When you look at the implementation, it all looks OK—if `rates` are `trending` , we will get an exchanged amount of money wrapped in `Some` . However, on closer inspection, there is no way executing an `IO` returned from this function can return `None` . Whenever we don’t have a trend, we recursively call the same function, and then it can, again, return a `Some` or call itself one more time. And so on ... Again, when we get trending rates, we return a pure value with no additional recursive calls. This is the recursion base case. ![](/images/book/grokking-functional-programming/c5c5bbd5-c8c1-4366-b5eb-b880082b37f2.png) To sum it up, the program described by `exchangeIfTrending` can only return a `Some` , fail, or never finish at all. `Option` stayed in the signature unnecessarily when we rewrote the function from the version that didn’t try to make an exchange until it succeeded, but it just fetched three exchange tables and made a decision. That’s why we needed to indicate that the decision might have been negative (by returning `None` ). Now, **we can model a possible absence of a trend with possibly infinite recursive calls instead of an** `Option` . In other words, if there is no trend, the program doesn’t return, but it continues to search for it, indefinitely.

>

def exchangeIfTrending(amount: BigDecimal, from: Currency, to: Currency): IO[BigDecimal] = {    for {
    rates  <- lastRates(from, to)
    result <- if (trending(rates)) IO.pure(amount * rates.last) ①
              else exchangeIfTrending(amount, from, to)
  } yield result
}

① The only two changes we need are the signature and the if clause. Note that we don’t need to change the else clause because it already returns IO[BigDecimal] .

## Usefulness of infinite recursive calls                                                                 ![](/images/book/grokking-functional-programming/0a2caa55-94eb-4bbf-9f38-d6fd5b2e1f92.png) Q We just replaced a function that returns a program, which always returns something with a function that returns a program, which may not finish at all. Doesn’t it mean that, from the user’s perspective, such a program freezes (or hangs)? How’s that better? A It’s better in a few areas. The most important one is separation of concerns. The function’s responsibility is to create a program that will exchange a given amount of money when a rate is trending. That’s all. It doesn’t care about how many times it should try before giving up or how much time the user is able to wait for a result. These are different concerns! We only have a value that describes a possibly infinite program, and we know it will try to do its part. We can further transform this `IO` value into another `IO` value, which describes a program that times out after 60 seconds, 10 minutes, or trying 100 times. What’s important is that these are different concerns, which we are still able to implement. Functional programming allows us to easily separate them from the business logic, which just tries to fulfill the user’s exchange request. We are able to play with independent, but compatible, blocks.                                                                 ![](/images/book/grokking-functional-programming/80e464d0-60ee-4c8b-934b-5b464f9105ad.png) We will use this new recursion superpower to fix even more problems and get a cleaner overall design. Our next prototype is going to be a lot better! Let’s start by fixing the `lastRates` function. BTW, transforming an `IO` value into an `IO` value that has a timeout built in is as simple as calling the `IO.timeout` function! We’ll discuss this more in chapter 11. ``` for { table1 <- exchangeTable(from) table2 <- exchangeTable(from) table3 <- exchangeTable(from) lastTables = List(table1, table2, table3) } yield lastTables.flatMap(extractSingleCurrencyRate(to)) ``` Remember that `extractSingleCurrencyRate` returns an `Option[BigDecimal]` because sometimes the API may not return a `Map` that contains the currency we are interested in. `lastTables` is a `List[Map[Currency, BigDecimal]]` . When we `flatMap` with a function that returns an `Option` , `Option` s are converted to zero- or one-element `List` s. `None` s are converted to empty `List` s, and we end up with a `List` of `BigDecimal` s that may be smaller than three elements—even empty! So we may not be checking for trends of size three at all! We will fix this issue very soon, but first we need your help. For example, if `lastTables` contains two empty maps and a map with a single “to" currency key, we will yield a `List` with a single rate back, not three! ## Coffee break: Recursion and infinity ![](/images/book/grokking-functional-programming/073fdaa1-e0cc-4e05-9aa6-337ed6feef8d.png) Now, it’s your turn to practice recursion, laziness, and dealing with infinity. This is an exercise that will move us toward a better solution to this chapter’s problem—the implementation you provide here will be used in the final, stream-based solution! We’d like `lastRates` to always return a fixed amount of last rates, but before we are able to implement that, we will need you to implement a smaller helper function. **Your task is to implement a completely new function,** `currencyRate` , which will always return the latest rate between currencies: ``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] ``` Note that this function doesn’t return `IO[Option[BigDecimal]]` . That means it should try to get an exchange table until it gets what it needs. Functions at your disposal You will need to use three functions to make it happen—the ones you already know (and should have in your REPL session already): ``` def exchangeTable(from: Currency): IO[Map[Currency, BigDecimal]] ``` This function returns a value describing an API call that returns an exchange table for a given ( `from` ) currency. Next: ``` def extractSingleCurrencyRate(currencyToExtract: Currency) (table: Map[Currency, BigDecimal]): Option[BigDecimal] ``` This function extracts a rate of a single currency ( `currencyToExtract` ) from a given exchange table (note there may not be anything to extract; hence, the `Option` ). Finally: ``` def retry[A](action: IO[A], maxRetries: Int): IO[A] ``` As a bonus exercise, you may want to try to reimplement `retry` using recursion. `retry` wraps a potentially failing API call and retries it a given number of times before giving up. Let’s retry a maximum of 10 times for now. Remember to use the power of recursion and laziness. Moreover, we accept that your function may return an `IO` value, which, when executed, may never finish (this will happen where the `from` currency is never found in any of the exchange tables returned by API calls represented by the `exchangeTable` function). ## Coffee break explained: Recursion and infinity ![](/images/book/grokking-functional-programming/073fdaa1-e0cc-4e05-9aa6-337ed6feef8d.png)

❶

Here’s the signature of the function we need to implement. It will return a program description:

``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] = { for { ① } yield ??? } ``` ① We will need to return an `IO` , so it’s safe to assume we will need a for comprehension. Let’s start with that.

❷

We need an exchange rate between from and to currencies. An exchange table for from will come in handy:

``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] = { ① for { table <- exchangeTable(from) ① } yield ??? } ``` ① `table` is a `Map[Currency, BigDecimal]` . ① We started building an `IO` value that describes a program. Its first step is to fetch an exchange table for the `from` currency using an API call.

❸

Since exchangeTable describes a raw single API call, we need some protection:

``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] = { for { table <- retry(exchangeTable(from), 10) ① } yield ??? } ``` ① `table` is still a `Map[Currency, BigDecimal]` .

❹

Now we need to extract a single rate using extractSingleCurrencyRate :

``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] = { for { table <- retry(exchangeTable(from), 10) rate <- extractSingleCurrencyRate(to)(table) ① } yield ??? ② } ``` ① `extractSingleCurrencyRate` returns an `Option[BigDecimal]` , not an `IO` value that the `flatMap` inside this for comprehension expects. ② Compilation error!

❺

We need the pattern matching to transform the Option into an IO[BigDecimal] , which is then yielded:

``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] = { for { table <- retry(exchangeTable(from), 10) ① rate <- extractSingleCurrencyRate(to)(table) match { ② case Some(value) => IO.pure(value) case None => currencyRate(from, to) } } yield rate } ``` ① When the rate of the to currency is not found in the `from` ’s exchange table (i.e., we got `None` ), we just try again using a **recursive call** to itself. ② This is the **recursion base case** . When we have a rate, we return it. ## Creating different IO programs using recursion

So far, we’ve been getting rid of Option from the signatures in favor of a potentially infinite execution. We previously used Option , which was meant to indicate that no rate satisfied the trending condition :

def exchangeIfTrending(    amount: BigDecimal, from: Currency, to: Currency
): IO[Option[BigDecimal]]

1

We used recursion to create values that describe programs that may run infinitely when executed.

The new version of the function tries to exchange the given `amount` , until it succeeds, so we can drop the `Option` altogether: ``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] ``` We used the same approach to implement `currencyRate` . It tries to find the rate until it succeeds: ``` def currencyRate(from: Currency, to: Currency): IO[BigDecimal] ``` Just for the sake of completeness, let’s mention that we could also implement it differently with an `Option` inside. This implementation would probably try once and return `Some` if successful or `None` if not: ``` def currencyRate(from: Currency, to: Currency): IO[Option[BigDecimal] ```

As we discussed earlier, we won’t be having any frozen or unresponsive programs. We are talking about IO values that represent infinitely running programs. But nobody has run them yet! We can still compose them with other IO values and change the final behavior.

A second way we can use recursion in real-world IO-based programs is to make sure another program—like an API call—is executed exactly n times and the results of all calls are available as a List of n elements. This may sound familiar to you, since we previously used List.range , map , and sequence to solve such issues. Here, we will briefly present a recursion-based alternative, so you are aware of both approaches.

To show this using an example, we will try to parametrize lastRates , so trends can be calculated based on lists of a specified number of rates. We’ve used n=3 so far, but we need to give our users the ability to specify a different number as a function parameter. We can use the new currencyRate function that returns IO[BigDecimal] (without Option ) and already uses retry , exchangeTable , and extractSingleCurrencyRate internally.

2

We can also use recursion to create values that describe programs making an arbitrary number of calls.

Recursion is useful in non-IO contexts as well, e.g., List is a recursive data structure: it is defined as its first element (head) plus another List (tail).

## Using recursion to make an arbitrary number of calls Let’s see how to use recursion to make as many API calls as needed to get exactly `n` last rates of a given currency pair ( `from` - `to` ). Here’s the current version of `lastRates` : ``` def lastRates(from: Currency, to: Currency): IO[List[BigDecimal]] = { for { table1 <- retry(exchangeTable(from), 10) table2 <- retry(exchangeTable(from), 10) table3 <- retry(exchangeTable(from), 10) lastTables = List(table1, table2, table3) } yield lastTables.flatMap(extractSingleCurrencyRate(to)) } ``` `currencyRate` Wrapper around the impure API call. Returns a description of a program that returns a rate at which you can convert from one currency to another. It may not finish if getting the rate is impossible. Let’s add a new parameter and try to reimplement the function, using the new `currencyRate` we’ve just implemented: ``` def lastRates(from: Currency, to: Currency, n: Int): IO[List[BigDecimal]] ``` There are two ways we can implement this function: Using sequence We used this approach in chapter 8, and it's still a viable option.

>

def lastRates(from: Currency, to: Currency, n: Int): IO[List[BigDecimal]] = {    List.range(0, n).map(_ => currencyRate(from, to)).sequence ①
}

① We crate a List of n IOs and then sequence it to create an IO of n-element List .

Using recursion Just for the sake of completeness, we can achieve exactly the same result using recursion.

>

def lastRates(from: Currency, to: Currency, n: Int): IO[List[BigDecimal]] = {    if (n < 1) {
    IO.pure(List.empty)                                ①
  } else {
    for {
      currencyRate   <- currencyRate(from, to)
      remainingRates <- if (n == 1) IO.pure(List.empty) ①
                        else lastRates(from, to, n - 1)
    } yield remainingRates.prepended(currencyRate)
  }
}

① These are recursion base cases . As you can see, we can have more than one.

We call `lastRates` recursively whenever n is larger than 2. Note that calling `currencyRate` is the first step of this function, and as you probably remember, it will return a single rate (or fail or continue indefinitely). Hence, we can be sure that when we reach the second step of the for comprehension, we already have one `currencyRate` . Now, we need to make a decision: do we need more rates or not? **If so, we recursively call `lastRates` but with a smaller `n`** . This is how we can be sure the function converges to the base case. No matter which version we choose, we get a `List[BigDecimal]` that is `n` elements long. The program may run infinitely though. ## Problems with the recursive version

Now we have the lastRates function that takes the additional n parameter. We also know that it will return a list of last n rates and will try to get it until it succeeds. We can use the new version of lastRates to update our solution to this chapter’s problem.

>

def exchangeIfTrending(    amount: BigDecimal, from: Currency, to: Currency
): IO[BigDecimal] = {
  for {
    rates  <- lastRates(from, to, 3) ①
    result <- if (trending(rates)) IO.pure(amount * rates.last) 
              else exchangeIfTrending(amount, from, to)
  } yield result
}

① We can now be sure that rates is going to be a n -element list.

Here’s how we’d use it:

An `IO` value that this function returns describes a program that will return a result, fail, or will continue executing indefinitely.

>

exchangeIfTrending(BigDecimal(1000), Currency("USD"), Currency("EUR"))  → IO
We got an `IO` value back, which you can try to `unsafeRunSync()` ! You should get back an amount in euros. We got a value describing a program that, when executed, will try to exchange 1,000 USD to EUR but only when there is a trend of three increasing rates from USD to EUR. However, when you look closer at what’s happening inside, the function doesn’t work very well performance-wise, especially when you take into account how expensive API calls usually are: - It always fetches three (or `n` ) rates first, then it makes a decision, and if it’s not successful, it fetches three again. Hence, even though six rates were fetched in total, only the first triplet and the second triplet are analyzed, ignoring potential trends in between. For example, if a first analyzed batch is **`[0.77, 0.79, 0.78]`** and the next batch is **`[0.80, 0.81, 0.75]`** , the current version would not find a trend of **`[0.78, 0.80, 0.81]`** , which exists in the middle. We need to analyze _sliding windows_ of rates to make the most of the API calls we have already made (and paid for). Processing data in isolated batches is a very popular paradigm, but it has its disadvantages. One of them is that sometimes valuable information is lost in the process of splitting data. - It runs as quickly as possible, so it may fetch **`n`** rates even in milliseconds. Practically, there is little chance that the rates change in such a small time frame. We need to make calls at a _fixed rate_ . Solving the issues above would be possible to achieve using the FP tools we already know ( `IO` and recursion) or imperatively. However, it’d take a substantial amount of time to get right, for many programmers. There are lots of corner cases to handle. **We need a different approach** . Remember that we don’t want to just solve these problems. We want to solve them in a readable and maintainable way with separation of concerns in mind. ## Introducing data streams There is a better approach to implement sliding windows, delays, and fixed rates. This approach is especially useful when we work with an unspecified amount of data, in our case data fetched from API calls. We have shown the classical approach to handle such problems, using recursion. We also briefly touched on the subject of separation of concerns; we want isolated modules that handle different aspects of the functionality: Having unspecified amounts of data means that our function may need to fetch and process 1, 10, hundreds of thousands, or infinite data entities before making a decision. This is something we need to accept and deal with separately. - One function should be responsible for fetching (e.g., last `n` rates or a single exchange rate between a given currency pair). - Another function should be responsible for aspects like timeouts, delays between calls, and retries. All these characteristics, together with a possibly infinite execution, usually hint at a usage of a different architectural approach: **streams** . As we will soon find out, using streams helps us invert the control and, therefore, isolate even more pieces of functionality without sacrificing any performance metrics. So far, the `exchangeIfTrending` function has been making API calls explicitly, adding the business logic on top of API results. With streams we will invert this dependency and use **a lazily evaluated infinite stream of IO-based API calls,** which will be defined elsewhere. We will break this long definition down for you on the following pages. We will use this knowledge to implement a far superior, bulletproof, and readable solution to this chapter’s original problem. ![](/images/book/grokking-functional-programming/91020fe8-5322-4105-b9e9-c7317137b93f.png) ## Streams in imperative languages Note that we discuss Java’s Stream here only to establish some common context. We are not going to use it in this book. Before we meet the functional `Stream` type, let’s first talk about something you may be more familiar with: Java’s `Stream` type. Java’s `Stream` has been around for some time now. It’s Java’s way of copying and introducing some of the functional concepts into the language. Let’s take a look. ``` Stream numbers = Stream.of(1, 2, 3); ① static Stream oddNumbers(Stream numbers) { ② return numbers.filter(n -> n % 2 != 0); } Stream oddNumbers = oddNumbers(numbers); ③ List result = oddNumbers.collect(Collectors.toList()); ④ ``` ① We define a finite stream of numbers. This stream emits (or generates) three values. ② Then, we define a pure function that takes one `Stream` and returns another, internally filtering only numbers that are odd. ③ We can then call this function and get another `Stream` back. ④ The `result` is `[1, 3]` . First of all, there is no mutability involved while we work just on the `Stream` type. Secondly, nothing is really computed until somebody wants to transform the `Stream` _value_ into something different, such as a `List` (using `collect` ) or a number (using `count` ). In Java, we say that `filter` , `map` , and other _functional_ stream operations—pure functions that take `Stream` s and return `Stream` s—are **intermediate operations** \* , while the functions that take us out of the `Stream` world (like `collect` ) are **terminal operations** + . \* All this may be treated as yet another proof that functional programming ideas are slowly making their way into many mainstream languages. + Sometimes you may see that instead of terminal operations, some say that a stream has a consumer. We will expand on this soon. Java’s `Stream` vs. `IO` I think it’s pretty easy to see a small, but important, resemblance between `Stream` and `IO` types. They both describe something without executing anything. A `Stream` value stores all the operations for a given stream, and they are executed only after using a terminal operation. An `IO` value stores all the side-effectful operations, which are executed only after using `unsafeRunSync` . The `Stream` type provides functions that return new immutable `Stream` values (think `filter` , `map` , and others). The `IO` type provides functions that return new immutable `IO` values. This comparison may be—and definitely is—a little too far-fetched, but it’s important to understand these similarities and where they are coming from. They are both implementations of immutability and lazy evaluation we’ve been talking a lot about in this book. Unfortunately, Java doesn’t allow us to reuse a `Stream` value. Once we use a `Stream` value, we can’t do it again. So it’s not really immutable, it just acts as immutable. ## Values on demand Some of you may have encountered another approach to explain how Java’s `Stream` type works: it’s _generating_ (or _emitting_ ) values on demand. Some people say that such streams are _cold_ —they need a consumer to even start generating values. However, **it’s just another way of explaining lazy evaluation** . It’s also just another way of allowing us to create an infinite stream of values. When we use lazy evaluation, we can, without any hesitation, create streams that are able to generate any number of values. In practice, however, they only generate values that are really needed at the client side— **on demand** . Here’s an infinite stream of values in Java: We define an infinite stream of numbers and then we call `oddNumbers` that return another infinite `Stream` back. We manipulate values, and nothing else happens. ``` Stream infiniteNumbers = Stream.iterate(0, i -> i + 1); Stream infiniteOddNumbers = oddNumbers(infiniteNumbers); ① // infiniteOddNumbers.collect(Collectors.toList()); Stream limitedStream = infiniteOddNumbers.limit(3); ② List limitedResult = limitedStream.collect(Collectors.toList()); ③ ``` ① The following line, if uncommented, would try to collect all the elements from an infinite stream to a list, which would freeze the program: ② Instead we can state how many elements from the infinite stream we’d like to use (e.g., three). ③ We now have a finite stream on our hands, and we can safely `collect` . The `limitedResult` is `[1, 3, 5]` . Java `Streams` are not the only place where an imperative language implements such a mechanic. For example, in Python, we have a notion of **generators** . The code above could be written in Python as follows: ``` def infinite_numbers(): ① x=0 while(True): x=x+1 yield x def odd_numbers(numbers): ② return filter(lambda i: i%2 != 0, numbers) infinite_odd_numbers = odd_numbers(infinite_numbers()) limited_result = itertools.islice(infinite_odd_numbers, 3) ③ ``` ① This Python function returns a generator that returns numbers infinitely. ② This Python function takes a generator and returns another one using `filter` . ③ We use both functions and take only three elements from the infinite stream. At the end we get `[1, 3, 5]` back. ![](/images/book/grokking-functional-programming/937d3b90-66d2-4328-8e35-4e307dfdccec.png) A small snippet that shows these techniques are ubiquitous! Similar approaches can be found in Reactive Streams (JDK 9), RxJava, Kotlin’s `Flow` , and more. **They all have two things in common** .

Separation of concerns

Inversion of control

The place where we take a finite number of elements ( limit ) doesn’t know anything about how the stream was created. It doesn’t know how many elements it can have and how many transformations were needed—and vice versa, the stream just generates elements and doesn’t care about how they will be used.

The oddNumbers function is able to generate odd numbers without knowing how to generate all numbers. It doesn’t have to call or generate anything. It gets all it needs as a parameter in the form of a Stream and just uses it. The user of this function has control now.

## Stream processing, producers, and consumers We now know that the streaming paradigm has been implemented in many languages. It has a lot of advantages because it uses the power of lazy evaluation and helps **decouple our modules** —especially when we deal with lots of incoming data that we need to process. When you decouple modules, you make them more independent of each other. Both separation of concerns and inversion of control represent an approach to decoupling. Let’s get our definitions straight before we move on. **Stream processing** means transformations of values representing infinite streams of values. When we do stream processing, we focus on operations on data first. However, the data needs to be stored somewhere—it needs to have a source. The output of the stream processing should also be used in one way or another. That’s why discussing stream processing inevitably brings up the topic of the **producer/consumer** pattern. ![](/images/book/grokking-functional-programming/76c42163-499c-4483-a11e-0004ac85eb59.png) We have just scratched the surface by talking about imperative streams. All of the streams we met so far have been operating on values generated locally in memory. However, the **streaming paradigm scales very well** . \* You can have streams operating on data coming from external APIs—as you will soon see—or any other external sources. There are lots of stream processing solutions out there, and they usually focus on different characteristics. But you can be sure that the general paradigm is the same. We want to separate different concerns by decoupling the source of the data, its processing, and its clients into isolated entities. On the producer side, we don’t know how many values the consumer will need, so we might just create lazily evaluated, potentially infinite streams of elements. On the consumer side, we don’t know anything about the source of data, but we are able to process it independently. \* The paradigm fits well when we program for more than a single machine. We’ll discuss multithreading in chapter 10. What’s important right now is that all the tools we learn here will apply there as well. ## Streams and IO As we mentioned earlier, we have only used streams of **values generated locally, in-memory** . We did it to show the idea and its general applications. However, our software usually is not that simple. We need to get data from the outside world and store it somewhere as well. Our current problem requires us to use an external API. Now that we understand the stream processing paradigm, we could envision the **external API as a producer** , which will produce exchange tables for a given currency as values. Note again that, although we talk about an external API being a producer, it won’t matter to its consumers, or clients of this data stream. A different function will be responsible for using exchange tables, but it won’t know where it will have originated from. However, it’s not that easy to implement at first sight. We’ve been trying to solve this problem functionally, using the `IO` type and some recursion. Additionally, we have used many other FP types and techniques extensively—they solve smaller parts of the problem, and they do it very well. The question remains: is it possible to use `IO` and other good bits of the existing solution inside a stream-based approach?                                                                 ![](/images/book/grokking-functional-programming/0a2caa55-94eb-4bbf-9f38-d6fd5b2e1f92.png) Q But do we really need `IO` in streams? Can’t we execute side-effectful impure functions directly? We could use something like Java’s `Stream.generate` that takes a function and emits as many elements as needed (calling the provided function for each of them). What’s wrong with that? A Unfortunately, although it is indeed possible, this approach is flawed in the same way normal impure functions are flawed. Imperative approaches tend to suffer from one very important flaw: **they don’t isolate side effects from pure functions** . Their APIs tend to treat both impure and pure producers as equals. For example: ``` Stream randomNumbers = Stream.generate(new Random()::nextInt); ① List randomResult = ② oddNumbers(randomNumbers).limit(3).collect(Collectors.toList()); Stream> usdRates = Stream.generate(() -> exchangeRatesTableApiCall("USD")); usdRates.limit(100).collect(Collectors.toList()); ③ ``` ① `Stream.generate` takes a Java function and uses it each time an element is requested. You may think of this as an infinite stream! ② `randomResult` is most definitely different each time we run it. In my case it was \[1816734507, 1516189193, 1552970581\]. ③ Here’s our API call function that may throw connection errors. Calling it 100 times almost guarantees getting an exception back. We already know now that purity needs to be isolated if we want to have more maintainable and testable codebases. Imperative stream versions won’t be enough. We need something that will let us use all the superpowers we learned about: `IO` and other immutable data types, pure functions, and lazy evaluation. **We need functional** `Stream` **s** . ## The functional `Stream` It’s time to meet the functional `Stream` type, which is a purely functional implementation of the stream processing idea. Since streaming is a very popular paradigm, many languages usually have more than one stream library available—each of them focusing on slightly different aspects. In this book we will show the `IO` -based approach, which, in Scala, is available using the `fs2` library. Note that this is a very different thing from Java’s `Stream` type we have discussed so far, although the general idea of having a producer, consumer, and a bunch of operators in the middle is exactly the same. The main difference is that the functional `Stream` embraces the inherent immutability and purity of FP. But the real deal maker is that we can reuse—and enjoy—a lot of functions and ideas we already know from using other functional types, including a seamless integration with `IO` values. In fact, a `Stream` value is analogical to `IO` because it only describes the stream processing program, just like an `IO` value describes a potentially side-effectful program. Note that the library choice is secondary, though. We want to show how functional programming libraries can work together and how the same ideas of immutable values and pure functions are used in different contexts. You learn a functional idea once, and you can apply it everywhere. Just like with other functional solutions, there are multiple different ways to spawn a `Stream` value. Showing them all is outside of the scope of this book, as this is not meant to be a comprehensive introduction to any particular library. It’s an introduction to a specific, functional mindset. Having that in mind, let’s create some `Stream` values. You need to `import fs2._` if you are not using the book’s `sbt console` REPL.

>

val numbers = Stream(1, 2, 3)               ①  val oddNumbers = numbers.filter(_ % 2 != 0) ①
oddNumbers.toList
→ List(1, 3)
numbers.toList                              ②
→ List(1, 2, 3)
oddNumbers.map(_ + 17).take(1).toList       ③
→ List(18)

① Both numbers and oddNumbers are streams of pure values, created and maintained in memory. It’s a use case very similar to what we saw with imperative streams. No IO yet!

② toList goes through each element emitted by the stream and returns all of them as a list.

③ We add 17 to each value emitted by oddNumbers and then take the first one (18).

No surprise here. We get exactly what we expect at this point: full immutability ( `numbers` and `oddNumbers` can be reused any number of times) and a set of well-named and defined functions ( `filter` , `map` , `take` , `toList` and more). A `Stream` is just a value. That means that if we need a stream with side effects (like API calls), we can define a lazily evaluated stream using recursion and encode it as a `Stream` of `IO` values just like the `Stream` of raw integers above. Additionally, we can convert a `Stream` value into an `IO` value and treat it just like any other `IO` value. So **functional** **`Streams`** **are just values—** even the most complicated ones! You can reuse a single stream value many times because it’s immutable. ## Streams in FP are values We’ve been working with immutable values, and streams are no exception. The `Stream` type takes two type parameters—they both explain a lot about what happens inside. Again, remember that we are just discussing a single stream library here. You might use this particular one soon, but it’s not what this book prepares you for. Focus instead on how all the FP mechanisms can work so well together. Immutable values, pure functions, laziness, and trustworthy signatures for the win! ![](/images/book/grokking-functional-programming/49176ff4-babf-43ad-b9af-21ae913b15df.png) Note **how much information is packed into a single type definition** . When you see a function that returns a `Stream[Pure, String]` , you can be sure that it returns an immutable value that describes a stream-based computation, which, **when executed** , will produce zero or more `String` values **in memory** . On the other hand, when a function returns a `Stream[IO, BigDecimal]` , you can be sure that it returns an immutable value that describes a stream-based computation which, **when executed** , will produce zero or more `BigDecimal` values potentially using and executing side effects under the hood. That means that all strategies and techniques related to side effects apply here as well.                                                                 ![](/images/book/grokking-functional-programming/0a2caa55-94eb-4bbf-9f38-d6fd5b2e1f92.png) Q But what does it mean to “execute" a `Stream` value? I understand that we can “execute" an `IO` value that describes a program, using `unsafeRunSync` . Does `Stream` has `unsafeRunSync` as well? A Not directly. Note that `Stream` describes a lazy producer of values. It won’t execute anything until there is a consumer that requests at least one element from this stream. `unsafeRunSync` is only needed when a `Stream` value describes a side-effectful computation (has `IO` as the first type parameter). But even then nothing happens if there is no consumer for any stream: ``` val numbers = Stream(1, 2, 3) val oddNumbers = numbers.filter(_ % 2 != 0) ``` The function we passed to `filter` won’t be executed until there is a consumer that requests at least one element. Here’s one possible consumer: `oddNumbers.toList` . Here we show an example of a pure stream because we haven’t shown an `IO` -based one yet. What matters is the concept, which is the same in both types. ## Streams are recursive values Before we move on to the IO-handling streams for good, let’s play more with streams of primitive values and learn how to handle them using the familiar FP techniques. Here’s how you can `append` a stream at the end of another stream:

>

val stream1 = Stream(1, 2, 3)  val stream2 = Stream(4, 5, 6)
val stream3 = stream1.append(stream2)
stream3.toList    ①
→ List(1, 2, 3, 4, 5, 6)

① We don’t consume anything from any of the three streams until stream3.toList is called. Only then the stream3 definition is used and only then values from stream1 and stream2 are used, indirectly.

Again, streams are just values, so you can `append` a stream to itself:

>

val stream4 = stream1.append(stream1)  stream4.toList
→ List(1, 2, 3, 1, 2, 3)
Here we create a stream that produces fewer values than another one:

>

val stream5 = stream4.take(4)  ①  stream5.toList
→ List(1, 2, 3, 1)

① Note that stream5 is yet another stream. We haven’t consumed any elements at this point. It’s just a producer that produces a maximum of four elements.

As you probably expect, functional streams take laziness very seriously— `append` **is lazy!** Hence, in order to create an infinite `Stream` , we can use the `append` **\+ recursion combo** without any hesitation.

>

def numbers(): Stream[Pure, Int] = { ①  Stream(1, 2, 3).append(numbers())    ②
}

val infinite123s = numbers()

infinite123s.take(8).toList          ③
→ List(1, 2, 3, 1, 2, 3, 1, 2)

① numbers is a function that returns a value, which represents a stream-based computation that produces integers without any side effects.

② We append a stream described by calling the numbers function at the end of Stream(1, 2, 3) . This is a recursive call! Nothing blows up, because append doesn’t eagerly evaluate what’s passed. It makes the recursive calls only when a consumer demands values, not earlier—it’s lazily evaluated.

③ numbers is a recursive function that produces a recursive value . When we take eight elements, numbers is called three times.

![](/images/book/grokking-functional-programming/c7a28015-34d8-48ee-97bb-7e4e593e03e8.png) If a consumer requests more than three elements, `numbers` are called recursively. ## Primitive operations and combinators The `Stream` type has a lot of functions defined inside. Remember that this is a standard functional API, so a majority of functions take `Stream` values and return new `Stream` values. We divide them into primitive operations and combinators. Their differences lay in their internal implementations. Primitives are functions that are implemented without using any other API functions. `append` , which we met earlier, is a primitive. Combinators are functions that are defined in terms of other API functions (primitives or other combinators). That means that we, as developers, can **choose from a variety of different options when implementing a particular functionality** , as we’ll soon see. Having many options means we can pick the one that best fits in terms of readability. It’s useful to understand the difference between primitive operations and combinators, because this idea comes up in many functional APIs. This way we can build a common vocabulary with other developers. We have used combinators on `IO` , for example. For example, we have just implemented an infinite stream using `append` and recursion. It turns out that we can use the `repeat` function to achieve the same result ( `repeat` calls `append` and itself recursively, but it’s hidden from us). Therefore, we can write So, `repeat` is a combinator because it’s defined in terms of `append` .

>

val numbers = Stream(1, 2, 3)①  numbers.take(8).toList   ①
List(1, 2, 3, 1, 2, 3, 1, 2)  ①

① An infinite stream of 1, 2, 3, 1, 2, 3, 1, 2, 3, ...

No matter what stream solution your team chooses for your next project, it’s usually a very good idea to go through its API and documentation and see how all functions, especially combinators, are implemented internally. This will give you a lot of insight into how this particular API should be used and what its strengths are.

We will use a small subset of primitive operations and combinators in this book, but if you are able to master them, you will be able to use any of the remaining ones with some help from the API documentation. It’s also worth mentioning that the majority of functions in this particular stream library are useful for both pure and IO-based streams. Quick exercise

Let’s make sure we are on the same page with regards to pure streams before we tackle IO. What do the following expressions return?

  1. Stream(1).repeat.take(3).toList

  2. Stream(1).append(Stream(0, 1).repeat).take(4).toList

  3. Stream(2).map(_ * 13).repeat.take(1).toList

  4. Stream(13).filter(_ % 2 != 0).repeat.take(2).toList

Answers:

List(1, 1, 1),

List(1, 0, 1, 0),

List(26),

List(13, 13).

## Streams of IO-based values You now probably agree that functional streams of primitive values are pretty useful, right? Hold your breath—their real superpower comes from their integration with the `IO` type. All we learned about `IO` and handling side effects is going to be used in side-effectful streams as well! The whole idea in one sentence goes like this: **we can have streams of** `IO` **values that will be automatically executed, on demand, when someone else consumes elements from the stream** . But until someone does, we just operate on immutable values. Let’s break down this idea to really grok what it means in practice. We will explain it, starting from the impure side-effectful Java function that casts the die. ![](/images/book/grokking-functional-programming/f5c89a39-0944-4296-8f77-8d7cd685aadb.png) Previously, we just called such a function as many times as we wanted, inside a for comprehension because the requirements allowed us to do so (e.g., “cast the die _twice_ ”). But let’s imagine we have a situation similar to the currency exchange case—that is, we don’t know up front how many times we need to call this particular `IO` value to get what we want. An example would be a requirement to cast the die until we get a six! It could be at our first try or never at all. Hence, it’s a small representation of a bigger problem we are facing in the currency exchange case. Let’s learn how the functional `Stream` can help us here. We need to do that to be able to write pure functions and take advantage of their benefits. “Delayed" side-effectful actions will be executed outside the functional core when we call `unsafeRunSync` .

>

val dieCast: Stream[IO, Int] = Stream.①  val oneDieCastProgram: IO[List[Int]] = dieCast.②

① dieCast is a Stream of a single IO value. eval takes an IO value and “evaluates” it (i.e., executes the given IO value and emits the Int produced by this IO action but only when a consumer requests it later on!).

② By calling .compile.toList on the dieCast stream, we transform it to another value: IO[List[Int]] . This is exactly the same IO that we learned about in chapter 8. We know how to deal with that!

We, therefore, got a description of a program that, when executed successfully, will produce a `List[Int]` . And since we know that `dieCast` is a one-element stream ( `eval` takes an `IO` and returns a `Stream` value that produces just a single value based on this `IO` , when requested), we should get a one-element list back. Let’s manually execute the `IO` value.

>

oneDieCastProgram.unsafeRunSync() ①  → console output: The die is cast ①
→ List(4)    ①

① “The die is cast” is written to the console because it’s a side effect, not the result of the function, which, in this case, was List(4) . (Yours may differ, since it’s random.)

## Infinite streams of IO-based values The functions we have just met, `eval` and `compile` , are very important when dealing with IO-based streams. Here are their summaries.

eval

compile.toList

Stream.eval creates a new Stream value that, when used by a consumer, will produce one Int value, based on the result of a side-effecting program described by an IO value passed as the single parameter:

A Stream value can be compiled to an IO value describing a side-effectful stream-processing program by calling the compile function. There are a few options we can compile a stream to, and we will use more of them later. The first one, compile.toList , makes sure that the underlying stream is processed, all its elements are consumed, and added to a List that is then returned as a result of the whole execution:

We will use them a lot in the remaining part of the chapter. Additionally, we will use functions we met when we dealt with pure streams. For example, we already know that we can transform any `Stream` value into an infinite stream that repeats the original one recursively by using the `repeat` combinator. It turns out that `repeat` works for IO-based streams as well. Hence:

>

val infiniteDieCasts: Stream[IO, Int] = Stream.eval(castTheDie()).repeat  val infiniteDieCastsProgram: IO[List[Int]] = infiniteDieCasts.compile.toList
So far, so good. We have two immutable values: a `Stream` and an `IO` . `compile.toList` transforms a `Stream` into an `IO` that, when executed successfully, will result in a list of all `Int` s produced by the stream. But are we really able to fit an infinite number of integers in a `List` ? ``` infiniteDieCastsProgram.unsafeRunSync() ① → console output: The die is cast → console output: The die is cast → console output: The die is cast ... ``` ① This program will continue running indefinitely!     Do not run it if you want to keep your REPL session intact.) THIS IS BIG! Types tell a lot about the internals in both IO and streaming programs. No! When we execute this value, it just writes to the console, which means the `IO` action has been executed. The program itself never finishes. It just overflows the console with lots of “The die is cast” messages that won’t stop appearing until we quit the application. We will never get a `List[Int]` back because there is no limit to how many elements the stream produces. But that doesn’t mean this program is useless. **The side-effectful actions are being executed** . That’s useful! ## Executing for side effects In fact, programs that are running until manual termination are pretty common. We are running them only for the side effects they are making. We don’t care what they produce at the end. We can even encode this in the type: `IO[Unit]` is exactly the type we expect when we have a value describing a program that is executed only for its side effects. We have already used this type when we used an API call that stores data for a future use. There are lots of other cases where we may be interested only in side effects: user interfaces, handling server endpoints, and socket connections. In our current die-casting scenario, our only side effect is the single log line we print each time we cast the die. However, we used `compile.toList` even though the stream is infinite, and there’s no way it will ever return a list. Streams have us covered for this opportunity as well. Let’s use **`compile.drain`** instead, which does exactly what we need. It “drains” the stream and returns `Unit` when it finishes. We get exactly the same infinitely running program, but the `IO` value doesn’t have any illusions about returning a list in the near future. Now, it’s `IO[Unit]` , thanks to the `drain` usage. This return type means we’ll run this `IO` value purely for the side effects it describes. In chapter 10, we’ll make this concept even better by returning `IO[Nothing]` . Stay tuned!

>

val infiniteDieCasts: Stream[IO, Int] = Stream.eval(castTheDie()).repeat  val infiniteDieCastsProgram: IO[Unit] = infiniteDieCasts.compile.drain

infiniteDieCastsProgram.unsafeRunSync() ①
→ console output: The die is cast
→ console output: The die is cast
→ console output: The die is cast
...

① This program will continue running indefinitely!     Do not run it if you want to keep your REPL session intact.)

Infinite streams are useful, but whenever we want to get some values back—not just side effects—we need to transform them into finite streams by using `Stream` functions. One of them is `take` , which will work for IO-based streams exactly like it did for pure ones.

>

val firstThreeCasts: IO[List[Int]] = infiniteDieCasts.take(3).compile.toList  firstThreeCasts.unsafeRunSync()
→ console output: The die is cast
→ console output: The die is cast
→ console output: The die is cast
List(6, 2, 6)
We can use `filter` to filter only values that are interesting to us. In this case, we wanted to throw the die until we get a `6` : ``` val six: IO[List[Int]] = infiniteDieCasts.filter(_ == 6).take(1).compile.toList ① six.unsafeRunSync() → console output: The die is cast ② → console output: The die is cast ② → console output: The die is cast ② → console output: The die is cast ② List(6) ``` ① Note that `filter` operates on `Int` s that will be returned by executing `IO` values in the future. In this sense, it works like `flatMap` inside the for comprehension. We can define functions that operate on values that are not yet available. ② As you see, in this case, four IO calls were enough to get the first `6` . Your mileage may vary! ## Practicing stream operations ![](/images/book/grokking-functional-programming/3f5cf784-59d6-46a6-8cdf-0a039204ac9b.png) It’s your turn to feel the power of functional stream processing. In this exercise you are going to use the `infiniteDieCasts` stream value: ``` val infiniteDieCasts: Stream[IO, Int] = Stream.eval(castTheDie()).repeat ``` **Your task is to create the following** `IO` **values.** Each of them should internally use numbers (and side effects) produced by `infiniteDieCasts` and do the following: 1. Filter odd numbers, and return the first three such casts. 2. Return the first five die casts, but make sure all `6` values are doubled (so a **`[1, 2, 3, 6, 4]`** becomes **`[1, 2, 3, 12, 4]`** ). 3. Return the sum of the first three casts. 4. Cast the die until there is a 5 and then cast it two more times, returning three last results back (a 5 and two more). 5. Make sure the die is cast 100 times, and values are discarded. 6. Return the first three casts unchanged and the next three casts tripled (six in total). Remember that each subtask should be represented by an `IO` value, not the `Stream` value; that means that you need to `compile` the `Stream` and transform it into a properly typed `IO` value that can be immediately executed. If the above exercises were too easy, here’s one that uses a combinator we haven’t introduced, but a very useful one: `scan` . It behaves exactly like `foldLeft` , but it works on `Stream` s and returns a `Stream` that additionally emits an accumulator value each time the internal aggregation function is called. You can also use `scan` to solve #3 above!           7. Cast the die until there are two `6` s in a row. Answers ``` 1. infiniteDieCasts.filter(_ % 2 != 0).take(3).compile.toList 2. infiniteDieCasts.take(5).map(x => if (x == 6) 12 else x).compile.toList 3. infiniteDieCasts.take(3).compile.toList.map(_.sum) 4. infiniteDieCasts.filter(_ == 5).take(1) .append(infiniteDieCasts.take(2)).compile.toList ① 5. infiniteDieCasts.take(100).compile.drain 6. infiniteDieCasts.take(3) .append(infiniteDieCasts.take(3).map(_ * 3)).compile.toList 7. infiniteDieCasts .scan(0)((sixesInRow, current) => if (current == 6) sixesInRow + 1 else 0) .filter(_ == 2).take(1).compile.toList ``` ① How hard would it be if we needed to return all casts in #4—not just the last three? ## Using streams to our advantage Now we know enough to tackle the chapter’s original problem. We designed the whole functionality bottom-up, and we succeeded, although the for comprehension–based function wasn’t as good as we wanted. The good thing is that we don’t have to start over. We used the functional approach and created a few small functions that have single, isolated responsibilities. We can reuse them in our new prototype without any changes! Step 3 **Using `IO` with `Streams` .** ``` def trending(rates: List[BigDecimal]): Boolean def extractSingleCurrencyRate(currencyToExtract: Currency) (table: Map[Currency, BigDecimal]): Option[BigDecimal] ``` **Remember that we also have the API call, which was given to us from outside. We, as functional programmers usually do, wrapped it in `IO` , so we can reason about it with clarity—in a referentially transparent way:** ``` def exchangeTable(from: Currency): IO[Map[Currency, BigDecimal]] ``` **We used all three functions, `IO` , and recursion to create a working version of `exchangeIfTrending` . However, we encountered two very serious problems when we tried to use it:** 1. **It always fetches three (or `n` ) rates first, then makes a decision, and if it is not successful, fetches another three again. Hence, even though six rates were fetched in total, only the first triplet and the second triplet are analyzed, ignoring potential trends in between. For example, if a first analyzed batch is `[0.77, 0.79, 0.78]` and the next batch is `[0.80, 0.81, 0.75]` , the current version would not find a trend of `[0.78, 0.80, 0.81]` , which exists in the middle. We need to analyze _sliding windows_ of rates to make the most of the API calls we have already made (and paid for).** 2. It runs as quickly as possible, so it may fetch **`n`** rates even in milliseconds. Practically, there is little chance that the rates change in such a small time frame. We need to make calls at a _fixed rate_ \*. \* We need to introduce a delay between consequent API queries.

I hope you see where this is going. We can solve both problems using functional streams! The first problem seems pretty straightforward, and we will start with it. The second looks scarier, but I promise that it’s not that bad! We are going to learn a few more stream combinators and end up with a very small and clear solution to the rate exchange problem. The trick is changing the mindset (and the architecture) to a stream-based one. We need a different view on API calls—instead of making them, we need to consume a stream of them.

Pay attention to all the new combinators we will introduce! ## Infinite stream of API calls Let’s create an infinite stream of rates from one currency to another. This will help us solve our issues by separating the concern of making individual API calls from the concern of detecting trends and making decisions based on them. This single change opens the door to a whole new world of design possibilities—it’s that powerful! As we go, please note that we don’t need to change any of the small functions we developed at the beginning. It’s yet more evidence that the design based on small, independent functions saves us a lot of time.

❶

We need a stream of rates between a pair of currencies. We can easily come up with a signature:

``` def rates(from: Currency, to: Currency): Stream[IO, BigDecimal] = { ① } ``` ① This function returns a value representing a side-effectful stream of `BigDecimals` , which are exchange rates between `from-to` currencies.

❷

Let’s start by creating an infinite stream of exchange tables of the from currency:

``` def rates(from: Currency, to: Currency): Stream[IO, BigDecimal] = { ① Stream ② .eval(exchangeTable(from)) .repeat } ③ ``` ① This is a stream of `Map[Currency, BigDecimal]` . ② We use the `Stream.eval` function to create a single-element stream that uses the provided `IO` action to produce a single `BigDecimal` . Then, we `repeat` this stream infinitely. ③ Compilation error!

❸

Since we now have a stream of maps and need a stream of BigDecimals , we must somehow extract a single BigDecimal rate from the map of all possible exchanges. Fortunately, we already have a function for that:

``` def rates(from: Currency, to: Currency): Stream[IO, BigDecimal] = { ① Stream .eval(exchangeTable(from)) .repeat .map(extractSingleCurrencyRate(to)) ② } ③ ``` ① This is a stream of `Option[BigDecimal]` . ② We `map` each value in the stream (each `Map[Currency, BigDecimal]` representing all `from` currency rates) using a function that extracts a single rate (for `to` currency). ③ Compilation error!

❹

We need to filter out None s and leave only values that were wrapped in Some . This can be achieved in a few different ways—one of them involves pattern matching—but, fortunately, there is a combinator that does that for us: unNone .

``` def rates(from: Currency, to: Currency): Stream[IO, BigDecimal] = { ① Stream .eval(exchangeTable(from)) .repeat .map(extractSingleCurrencyRate(to)) .unNone ② } ``` ① Now we have an infinite stream of rates between `from` and `to` currencies. ② `unNone` takes a stream of `Option[A]` values and returns a stream of `A` s, filtering out `None` s along the way. ## Handling IO failures in streams                                                                 ![](/images/book/grokking-functional-programming/0a2caa55-94eb-4bbf-9f38-d6fd5b2e1f92.png) Q What about failures ? IO actions may randomly fail, right? Side-effectful streams need to run underlying IO actions to produce an element. So what happens if evaluating one of the IO values fails? A Then, the whole stream fails too! But don’t worry. We can use retry strategies we learned about in chapter 8, such as the `retry` function. Additionally, it turns out that `Stream` has `orElse` too! How exactly does `orElse` work for streams? We have some experience in FP, and thanks to that we can get a sense of how this “new” functionality works by comparing it to what we already know. Remember that `IO` has the `orElse` function, too! ![](/images/book/grokking-functional-programming/e254637c-ce83-4b77-8947-5faf0f0ea50d.png) ## Separated concerns

We know how orElse works. Now we need to provide a Stream value that will be run in case the original stream fails. What value should we provide? Let’s assume that we want to just start over. Therefore, we can recursively call the same function again! This way we get an infinite failure-free stream of BigDecimal s, which are exchange rates from a given currency ( from ) to another ( to ).

``` def rates(from: Currency, to: Currency): Stream[IO, BigDecimal] = { Stream .eval(exchangeTable(from)) .repeat .map(extractSingleCurrencyRate(to)) .unNone .orElse(rates(from, to)) ① } ``` ① If anything goes wrong with this stream, do not fail. Instead, recover with the given fallback stream (which is exactly the same one). A great thing about streams, especially when we start filtering emitted elements, is that from the perspective of the stream’s consumer it doesn’t matter how many times an `IO` has been executed (or how many different IO actions have been used). The consumer has a function ( `rates` ) that returns a `Stream[IO, BigDecimal]` . When it wants just the three first rates between a `from` - `to` currency pair, it just says so.

>

val firstThreeRates = rates(Currency("USD"), Currency("EUR")).take(3).compile.toList  → IO[List[BigDecimal]]
But when executed, internally, the stream may call the `exchangeTable` API dozens of times for various reasons (e.g., a `Map` may not contain the `to` currency, or the API call fails or takes too long to complete). The producer needs to worry about these things (and handle them) by coding these concerns inside the `rates` function that returns a `Stream` . But the users (consumers) of this `Stream` don’t need to care about such small implementation details (at least for them). They may focus on higher-level functionalities like checking trends and making decisions based on them. **There are lots of concerns on both sides** , but using the `Stream` type, we can draw a very visible boundary between them. THIS IS BIG! Streams help to separate concerns in your application. ![](/images/book/grokking-functional-programming/75395013-f69e-4955-879c-6e4912cc8aae.png) ## Sliding windows We implemented the `rates` stream. Now we can take off our “ `rates` producer” hat and put on the “ `rates` consumer” one. We need to implement a new version of the `exchangeIfTrending` function using the `rates` stream that encapsulates all the nitty-gritty details regarding API calls and IO. We must solve the main problem as efficiently as possible, and that means we’ll need **sliding windows** (the `sliding` combinator).

❶

We will reuse the same signature of exchangeIfTrending . Let's start with just using the rates stream.

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) } ① ``` ① Compilation error!     `Stream[IO, BigDecimal]` ![](/images/book/grokking-functional-programming/4547e25e-e303-4012-bd1c-00980fbe8d81.png)

❷

In order to find a trend, we need a list of n elements. Fortunately, we can use streams’ sliding combinator that gathers the last n elements emitted by the source stream and emits them as an n -element Queue . We haven’t used the Queue type yet—it’s yet another immutable collection type optimized for adding and removing elements in the first-in-first-out (FIFO) manner. We implemented trending to get a List of rates and return a Boolean , so we need to map each Queue value to a List value using the toList function.

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .sliding(3) .map(_.toList) } ① ``` ① `Stream[IO, List[BigDecimal]]` ![](/images/book/grokking-functional-programming/a5d42540-e653-4b3a-8457-d8641dc2f0d7.png)

❸

Having a stream of three-element lists allows us to easily filter only the lists that are trending .

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .sliding(3) .map(_.toList) .filter(trending) } ① ``` ① `Stream[IO, List[BigDecimal]]` ![](/images/book/grokking-functional-programming/70936f68-b936-4f43-8d09-6b69171f5561.png)

❹

We now have a stream that will emit List values containing rates that are trending. A quick peek at the requirements tells us that we now need to use the last rate as a basis for our exchange. We know that we operate on non-empty lists so we can use List ’s last function. ( lastOption + unNone : is also a good choice.)

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .sliding(3) .map(_.toList) .filter(trending) .map(_.last) } ① ``` ① Stream\[IO, BigDecimal\] ![](/images/book/grokking-functional-programming/41940601-98ea-4074-95d5-d6824696f537.png)

❺

We don’t really need multiple trending rates. One is enough! Hence, we can just create a stream that emits a single element: take(1) . (fiere is also a head combinator that does exactly the same thing.) That’s all we need so we compile the stream, but this time we use lastOrError , which returns an IO value that takes the last element a stream produced before it finishes (or an IO failure if this stream finishes without emitting anything, which won’t happen in our case because the rates stream is infinite).

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .sliding(3) .map(_.toList) .filter(trending) .map(_.last) .take(1) .compile .lastOrError } ① ``` ① It compiles now! The function returns an `IO` value that describes a program that will do an unknown number of API calls and produce a `BigDecimal` value representing a trending rate. **It uses stream processing internally, but it’s hidden from clients of this function.** fiey see and use only a single `IO` value.

❻

The requirements say we need to exchange the given amount. This is something we already know how to handle using the standard IO -based approach. Here, let’s just return the total amount we’d exchange:

``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .sliding(3) .map(_.toList) .filter(trending) .map(_.last) .take(1) .compile .lastOrError .map(_ * amount) } ``` ![](/images/book/grokking-functional-programming/bf24dca8-e8fc-46a8-a954-0b68d8ecfbbf.png) **And that’s it!** We now have a working solution, based on streams. Note how we represented the streams graphically. This is a pretty common approach in both FP and stream processing paradigms. Here’s the full diagram that shows all the intermediate stream values. Remember that each stream is represented by an immutable `Stream` value! ![](/images/book/grokking-functional-programming/fb8a753a-211f-45f7-b70c-1cc5e79312e7.png) Note that each function returns a new immutable value. Nothing is changed or modified. We can reuse each of these values any number of times. ## Waiting between IO calls The last problem we want to address is that we make subsequent IO calls as quickly as possible, usually in milliseconds. This is OK for demonstration purposes, but in real life you’d quickly drain API call quotas without getting any real value out of them. It’s more practical to wait between API calls, cache them, or introduce some additional mechanisms. Let’s focus on waiting between calls for now. How can we achieve a fixed one-second delay between subsequent API calls using the stream processing paradigm? A quick search in the documentation results in the `Stream.fixedRate` function. If you are not using the book’s sbt console REPL, import `scala.concurrent.duration._` and `java.util.concurrent._` The `Stream.metered` combinator would work as well.

>

val delay: FiniteDuration   = FiniteDuration(1, TimeUnit.SECONDS) ①  val ticks: Stream[IO, Unit] = Stream.fixedRate[IO](delay)

① FiniteDuration is just a product type that is used to represent duration in the Scala standard library. Here we define a value representing duration of one second.

`ticks` is a `Stream` value that represents a stream that emits `Unit` values ( `()` ) every `1` second, once executed. The great thing about this stream is that it won’t block the running thread, while waiting to produce another value. `IO` -based programs, when executed, play fair and don’t use threads from your thread pools when they don’t need them. Additionally, remember that we operate on immutable values— `delay` and `ticks` above are just values—and we’ll only start caring about thread pools when we go outside the functional core, later on. We are inside the functional core, where we only have pure functions and no `unsafeRunSync` calls. Now that we have a stream of `ticks` that is time dependent, we can compose them with rates by **zipping** them.

>

val firstThreeRates: IO[List[(BigDecimal, Unit)]] =    rates(Currency("USD"), Currency("EUR"))
    .zip(ticks).take(3).compile.toList
firstThreeRates.unsafeRunSync()   ①
→ List((0.80,()), (0.79,()), (0.82,()))   ②

① When we execute it we can be sure that it will work at least three seconds. To execute it, you will need to import a default thread pool configuration: import cats.effect.unsafe.implicits.global .

② A list of tuples (BigDecimal, ()) .

When we **`zip`** two streams, we need to wait for an element from both streams to produce an element of the combined stream. This way, the rate of emitting values in the combined stream is the rate of the slower input stream. If API calls are quick, then the slower one is `ticks` . This may be counterintuitive at first, but since all functional streams are lazy, this approach ensures that **we don’t make API calls** (defined inside the `rates` stream) **more often than once a second** . There are more corner cases here, but the general approach to solving them remains the same. ![](/images/book/grokking-functional-programming/60608015-5506-4410-b032-b575b29deaa4.png) ## Zipping streams Step 3 ✔ **Using `IO` with `Streams` .** Note that when we `zip` two streams together, we get a stream of tuples back. Each tuple has an element from both streams, and its type is derived from the types of the elements emitted by each of the zipped streams. However, we sometimes don’t care about both elements because we use `zip` to slow down one stream using another stream like we did with `ticks` . For these occasions we have special versions of `zip` : `zipLeft` , which zips two streams but produces elements from the “left” stream, and `zipRight` , which zips two streams and produces elements from the “right” one.

>

val firstThreeRates: IO[List[BigDecimal]] =     rates(Currency("USD"), Currency("EUR"))
    .zipLeft(ticks).take(3).compile.toList
firstThreeRates.unsafeRunSync()   ①
→ List(0.85, 0.71, 0.72)   ②

① When we execute it we can still be sure that it will work at least three seconds.

② A list of BigDecimal s, because we used zipLeft ( rates are on the “left” of the .zipLeft call).

Now, we can create the final version of the `exchangeIfTrending` function, which behaves correctly and with a lot better performance. ``` def exchangeIfTrending( amount: BigDecimal, from: Currency, to: Currency ): IO[BigDecimal] = { rates(from, to) .zipLeft(ticks) .sliding(3) .map(_.toList) .filter(trending) .map(_.last) .take(1) .compile .lastOrError .map(_ * amount) } ``` ![](/images/book/grokking-functional-programming/1a5cb869-6430-4ade-8bc7-b367d4dbb45d.png) **And that’s a wrap!** We have a function that returns an `IO` value that describes a program that will make unknown number of API calls at a fixed rate of a maximum one call per second and will produce a given amount in the new currency only if the rates are trending. The **`IO`** value we return is still just a value and can be used in a bigger program as a normal building block. The fact that it uses a stream-based approach internally is just another implementation detail. Clients of this function get an `IO` value, and that’s what matters to them. ## Benefits of using the stream-based approach

We have shown just a small fraction of possible stream functions to give you an intuition of what’s possible. Whenever you have a new problem, it’s usually a good idea to explore the API of the functional type you are working with . Chances are high that there is a helpful and well-tested function already available (like sliding and zipLeft ).

There are several benefits of using the stream-based approach that are so compelling that many mainstream imperative technologies have included it in their APIs: - _Definition of a stream is separated from its use site_ —That means the definition may be infinite, and it will be up to the call site to define how many elements it really needs. - _Nothing is done until it’s really needed_ —All operations are lazily evaluated. - _The high-level API enables us to focus on the business domain instead of implementation details_ —It’s another example of essential versus accidental complexity. There are multiple examples of providing higher-level APIs and hiding details like paging, buffering, chunking, batching, and distributing workloads. Encapsulating implementation details is especially popular in big data paradigms like MapReduce. - _More separated concerns_ —Functions we pass as parameters to `Stream` combinators don’t know they are used inside a stream. - _Composability_ —Developers can analyze a larger functionality by understanding smaller, independent pieces first and then understanding connections between them. - _Encapsulating asynchronous boundaries_ —Another implementation detail (an accidental concern) is that we may be running many streams concurrently, potentially on different computers (nodes), and joining results together using a larger stream. This approach may encapsulate all the details of crossing boundaries between nodes and synchronizing their results. Synchronous vs. asynchronous So far in the book we’ve been doing synchronous, sequential computations (i.e., computations that don’t need more than one thread). In the last example, with the `ticks` stream, we have gently entered a new realm of multiple threads: asynchronous and non-blocking computations. It turns out that both `IO` and `Stream` values are useful in multithreaded, asynchronous environments as well! That’s something we are going to explore in the next chapter. Many existing technologies expose APIs that try to tap into these benefits. You may have came across some terms like FRP (functional reactive programming ), reactive programming, or reactive APIs. Such a “reactive” API usually mean that it includes combinators that operate lazily. **That’s the power of FP sneaking into the mainstream** . THIS IS BIG! Many languages and libraries try to use the power of FP by including stream-like lazy APIs. ## Summary Stream-based architectures are very popular in many scenarios. You can use much of what you learned here in the following use cases: - Streams are popular in UI programming (e.g., you get a stream of user clicks and can make some decision based on them similarly to our currency stream). - Streams are used in distributed computing, where we may have producers and consumers that produce and consume elements at vastly different paces on different nodes. This is where reactive streams help a lot—this was implemented as part of reactive streams initiative and included in Java 9 (see the **`Flow`** class). Many message-based systems choose reactive APIs by default. - The stream approach is very popular when dealing with big data (i.e., sets of data that can’t fit into the memory of a single computing node). This is a very broad definition, but it includes geographic data, paging infinite news and social feeds, and processing very big files and storing them (e.g., Hadoop/Spark). CODE: `CH09_*` Explore this chapter’s source code by looking at `ch09_*` files in the book’s repository. No matter your use case, you can use well-known stream functions in all of the above, using a streaming library of your choice. Some function names will be different, but your intuition will help you find the right one! The following sections discuss the skills we’ve learned in this chapter. Declaratively design complicated program flows We learned to define program flows that include API calls using stream functions like `map` , `filter` , `append` , `eval` , `take` , `orElse` , `sliding` , `zip` , `zipLeft` , `repeat` , and `unNone` . We also learned how to use immutable `Map` s and tuples—they both are ubiquitous in FP. When you iterate over `Map` s, you iterate over a list of tuples. When you `zip` lists, you get a list of tuples. When you `zip` streams, you get a stream of tuples. Use recursion and laziness to defer some decisions We saw how recursion helps us start over in many places. We used it to make IO calls until we got what we needed to recover from a failure. Handle IO-based streams of data Streams of integers and streams of IO-based integers are very different, but we still managed to apply the same techniques and a similar API to handle all of them. We also learned how streams in general help us separate the concerns and invert the control by moving the API call responsibility to a different place. Create and handle infinite stream of values The inherent stream functions’ laziness helped us create infinite streams. Isolate time-dependent functionalities We discussed a stream of `Unit` values produced every `1` second. We _zipped_ it with the API calls stream to produce a stream that emits values at a fixed rate. We gently entered the multi-threaded environment by doing so. Now it’s time to do a deep dive into the concurrent world.