In this chapter you will learn
-
how to design real-world functional applications
-
how to model more complicated requirements as types
-
how to integrate with real data-source APIs using
IO
-
how to avoid resource leaks
-
how to cache query results to speed up execution
“ What I cannot create, I do not understand. ”
—Richard Feynman
Make it work, make it right, make it fast
This quote has a long history, but the presented formulation is attributed to Kent Beck.
It’s time to put all the knowledge you’ve gained to a good use and implement something tangible! We will use all the functional tools and techniques we learned to follow some very old programming advice: first make the solution work, then make it work correctly, and, only then, think about making it fast. Following are the requirements, which, understandably, are a bit more involved than what we were used to.
Requirements: Pop culture travel guide
-
The application should take a single String value: a search term for the tourist attraction that the user wants to visit and needs a travel guide for.
-
The application needs to search for a given attraction, its description (if it exists), and its geographical location. It should prefer locations with larger populations.
-
The application should use a location to do as follows:
-
Find artists originating from this location, sorted by the number of social media followers
-
Find movies that take place in this location, sorted by the box office earnings
-
For a given tourist attraction, artists and movies form its “pop culture travel guide” that should be returned to the user. If there are more possible guides, the application needs to return the one with the highest score, which is calculated as follows:
-
30 points for a description
-
10 points for each artist or movie (max. 40 points)
-
1 point for each 100,000 followers (all artists combined; max. 15 points)
-
1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points)
-
We will add support for more pop culture subjects in the future (e.g., video games).
There is a lot to unpack here. A simple usage example is in order:
travelGuideProgram("Bridge of Sighs").unsafeRunSync()
→ Bridge of Sighs is a bridge over a canal in Venice. Before visiting,
you may want to listen to Talco and watch some movies that take place
in Venice: "Spider-Man: Far from Home" and "Casino Royale."
Here, we show a String result, but in reality we will return a nice immutable value containing all the information that can be used to create such a String .
Yes, this is exactly what the application we are going to develop in this chapter will be able to do! And not just for “ Bridge of Sighs ” but for any other tourist attraction described in Wikipedia ! This chapter is going to be mostly a code walk-through, but I strongly advise you to take your time and think about each problem we encounter before moving on to the solution. We will mark these problems in a specific way.
Let’s think about it first. What immutable values can you use to model the requirements above? Look for nouns, their properties, and how they will need to be used. | |
Modeling using immutable values
When requirements are provided in such a clear way, modeling using immutable values (product and sum types, or ADTs) is very straight-forward and is usually a very good first step in designing a new program. Let’s see how we can transform requirements into types in this case. | Algebraic data types ADTs were introduced in chapter 7. |
Look for subjects in requirements Model subjects as custom ADTs, built-in ADTs (like Options), or primitives:
Look for properties of subjects in requirements Model properties as fields in product types.
Look for subject usages Model usages as identification fields in product types.
Business domain modeling and FP
Modeling business domain concepts directly in the code may look familiar to those of you who at least once in their career were responsible for software architecture and needed to use concepts like domain-driven design (DDD ). This and other architecture design techniques are compatible with functional programming as long as you constrain yourself to use only pure functions and immutable values. The model design activity may seem a bit chaotic at first, but remember that there usually is some process you can follow and well-known techniques you can take advantage of. In the end, whether you follow DDD or another technique is up to you and your team. Once we are comfortable with the initial model, we can move on to designing the rest of the application. Remember that nothing is set in stone, so we may be forced to return to the model design phase when new requirements surface (we’ll see an example of that in chapter 12). | Requirements as types Modeling requirements as types was discussed in detail in chapter 7. ↑ As you see, we will additionally use this chapter to recap a lot of material from previous chapters. If you have trouble remembering how to approach some problems, please use provided bookmarks to schedule some additional chapter re-readings. |
> | object model { opaque type LocationId = String
object LocationId {
def apply(value: String): LocationId = value
extension (a: LocationId) def value: String = a
}
case class Location(id: LocationId, name: String, population: Int)
case class Attraction(name: String, description: Option[String], location: Location)
enum PopCultureSubject {
case Artist(name: String, followers: Int)
case Movie(name: String, boxOffice: Int)
}
case class TravelGuide(attraction: Attraction, subjects: List[PopCultureSubject])
}
import model._, model.PopCultureSubject._ |
This is the model we ended up with after following the requirements-based design process on the previous page.
Finally, note that we chose to use the same model for the whole application in all the layers. In bigger applications, however, it’s usually smarter to represent each concept depending on the context it appears in (again, see DDD and the concept of a _bounded context_ ). In our case, we could say that an `Artist` model is only viable in the context of calculating the score of a guide because this is where we need `followers` . We will use this class in other contexts as well, but we can imagine that for the final user presentation (e.g., in a UI) we might want a simpler artist model:
```
case class ArtistToListenTo(name: String) ①
```
① If you choose to follow such design advice, you are able to separate concerns better but at the cost of implementing additional mapping functions between `Artist` and `ArtistToListenTo` .
## Data access modeling
We can apply a very similar process to modeling the data access layer. Let’s look at our requirements and find IO-related functionalities. These will need to return our model values wrapped in an IO because we know some unsafe side-effectful actions will need to happen—data resides outside of our application, so reaching out to fetch it means there are some additional risks involved. | Input/Output actions IO actions and separation of concerns were heavily discussed in chapter 8. |
Look for **data access actions** ...and model them as pure function signatures.
“...find **artists** originating from this location..."
```
def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]]
```
“...find **movies** that take place in this location..."
```
def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]]
```
“The application needs to **search** for a given attraction..."
```
def findAttractions(name: String, ordering: AttractionOrdering, limit: Int): IO[List[Attraction]]
```
Look for **data access properties** ...and model them as types.
“It should **prefer locations** with larger populations...."
> | enum AttractionOrdering { case ByName
case ByLocationPopulation
}
import AttractionOrdering._ | → | The requirements don’t directly state that we will need different ordering options (we will need just the population-based ordering), but we use this example to show again how to use ADTs to make data access functions less error-prone and very readable. |
Separation of concerns
We ended up with three function signatures that represent the data access layer. Note that we don’t need to assume anything about where the data will come from. We may assume it’s going to be Wikidata, but we won’t encode this assumption in the code just yet. Similarly, we won’t choose any client library that talks with Wikidata, nor will we make any final decision about the query format. It’s usually wise to delay such decisions until the very last possible moment. That’s why having just function signatures is enough for now.
Coding to the interface
We can implement the business side of our program using only the data access functions defined above without having their implementations. We will of course need to encode the way to access the data and transform it to our domain model values eventually. But in the spirit of delaying as many decisions as possible, we will do it later in the chapter. You may recognize this technique from object-oriented programming as _coding to the interface_ . It’s a useful technique in FP as well. Signatures are our interfaces and function bodies are our implementations.
THIS IS BIG!
Many OO design principles can be used with pure functions and immutable values (FP).
## A bag of functions
When we have a bunch of functions that are usually used together or their implementations share many common expressions, we may be tempted to bundle them inside a bigger type: a **bag of functions** .
```
case class DataAccess(
findAttractions: (String, AttractionOrdering, Int) => IO[List[Attraction]],
findArtistsFromLocation: (LocationId, Int) => IO[List[Artist]],
findMoviesAboutLocation: (LocationId, Int) => IO[List[Movie]]
)
```
A value of type `DataAccess` will provide three pure functions. And since in FP languages functions are just values, `DataAccess` can be encoded as a product type. This is perfectly fine and usable, but some people find it hard to operate on product types that are just functions. They may find the lack of function parameter names misleading, too. That’s why we may implement the bag-of-functions pattern using an alternative approach akin to an interface from OOP.
> | trait DataAccess { ① def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]
def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]]
def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]]
}① We use the trait keyword in Scala to define an interface. Other languages may offer other encodings of the bag-of-functions pattern. |
As you see, these are the same three functions bundled together, but we use normal function signatures with parameter names instead of function types. You may treat the `DataAccess` type as a “signature” for a value. It’s a blueprint for a value, just like a signature is a blueprint for a function body, and an interface in OOP is a blueprint for its implementation. All these intuitions are valid. Most importantly, these three functions are pure functions, and any implementation of `DataAccess` must not have any internal state—it’s **just a bag of pure functions related to each other** .
We won’t provide bodies for `DataAccess` functions just yet!
We will first show how we can use a bare, unimplemented bag of functions ( `trait` ) in a business logic function. Separation of concerns FTW!
No matter which version (a product type or an interface) you choose, the benefits are the same. By using this pattern you will be able to:
- _Pass a single value to a function_ that needs data access functionalities instead of passing three individual function values; this benefit is more important when we have many different functions that require data access. In such a case all these bloated signatures would look very repetitive and make the code look messier.
- _Implement all the functions at once_ , using some common expressions.
We will show both benefits during the following implementation steps.
There is at least one disadvantage, too. It’s hard to find a good “common shared identity” for many functions. It’s not as bad here—we have three functions that share the “data access” identity. But this identity would not work in bigger programs because it would include a lot of functions.
Again, we just show what’s at our disposal. The final decision is always yours to make.
## Business logic as a pure function
**We have just** **finished the modeling phase!** We have all the types we need to finally start implementing the core functionality. Yes, our data access layer is not yet implemented, but this doesn’t mean we can’t implement the required business behavior. We will implement it as a pure function. As we wrote in the introduction, we are following the old advice by first aiming to make the whole thing work in at least one basic case. This has a very important consequence: we can quickly check which assumptions are correct and which need more thought. Our first approach is the simplest possible version that _works_ : a function that returns an `IO` value describing a program that returns a single travel guide. We won’t implement some of the requirements just yet—namely, the ones that define the scoring algorithm. Hence, we will try to return the first possible travel guide. Only then will we try to “make it right” by implementing the remaining requirements, including scoring and sorting possible guides.
We will focus on implementing the data access layer after implementing the first version of the main behavior. We are following the top-down design again! We think about the top-level function, its clients, and the interface before anything else.
❶ | Let’s start with the signature. We know that the user input is the name of the attraction, and the function needs to return a program which, when executed, will return a travel guide: |
```
def travelGuide(attractionName: String): IO[Option[TravelGuide]] = {
???
}
```
❷ | We first need to find attractions with a given name. That’s why we require a DataAccess parameter. This is a value that contains three data access functions, but we’ll use just one of them now: |
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 1) ①
} yield ???
}
```
① We call `findAttractions` to get an IO value describing a program that will try to find a tourist attraction that contains a given `attractionName` . We’d like to get a single attraction that resides in a geographic location with the largest population (order `ByLocationPopulation` and limit 1).
❸ | If we find any attraction, we look for artists and movies. Otherwise, we return None : |
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 1)
guide <- attractions.headOption match {
case None => IO.pure(None) ①
case Some(attraction) =>
for {
artists <- data.findArtistsFromLocation(attraction.location.id, 2) ②
movies <- data.findMoviesAboutLocation(attraction.location.id, 2) ②
} yield Some(TravelGuide(attraction, artists.appendedAll(movies)))
}
} yield guide
}
```
① We use pattern matching and provide two different IO values depending on whether we got `Some` or `None` .
② We get a maximum of two artists and two movies connected with a given location. To simplify the example, we don’t directly state how to order them—they will be sorted internally by followers and box office. However, the approach we showed in `findAttractions` would work here as well.
## Separating the real data access concern
We now have a function that implements some business requirements, but we don’t have a way to call it because we have no DataAccess value. | |
```
def travelGuide(
data: DataAccess, attractionName: String
): IO[Option[TravelGuide]] ①
```
① Again, `DataAccess` contains three values that are pure functions. `travelGuide` doesn’t have any idea how these functions are implemented.
We reached the point of the implementation process at which we can no longer delay choosing and implementing the real data access API. There are many data sources we could use here, including some custom SQL or NoSQL databases. **The main concern here is that the data access layer details don’t leak to other layers** . The `travelGuide` function uses a `DataAccess` value that exposes everything `travelGuide` will ever need to know without any internal details.
```sql
trait DataAccess { ①
def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]
def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]]
def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]]
}
```
① Again, `DataAccess` contains three values that are pure functions. `travelGuide` doesn’t have any idea how these functions are implemented.
To call travelGuide , we first need to create such a DataAccess value. We need to implement these three functions: each of them needs to return an IO value describing a program that fetches data from somewhere. Note that we may also use IO.pure with a hardcoded value there (like we did in previous chapters), but we promised you before that this chapter was going to be different: we want to show a real-world integration. We will use Wikidata , which is a collaboratively edited, multilingual, knowledge graph and a common source of open data that projects such as Wikipedia use. | |
This Wikidata description was taken from Wikipedia.
SPARQL query language
Wikidata allows us to query the data it exposes using the SPARQL query language. We won’t go into SPARQL details in this book—we will use just three queries as examples (attractions, artists, and movies). They won’t be optimized for production usage, and you don’t really need to understand them. Focus on the way we treat them: as some internal implementation detail which should not leak outside the `DataAccess` internals. The same principle would apply for SQL queries if we used MySQL as a data access layer or N1QL queries if we used Couchbase. **This concern is separated** .
Note that `DataAccess` is so generic that it allows us to provide implementations for a variety of data access solutions, including MySQL, Couchbase, and many more.
## Integrating with APIs using imperative libraries and `IO`
We need to create a value that implements the `DataAccess` “interface” (i.e., provides three pure functions with very specific signatures). We want to implement them so that they return `IO` values describing programs that connect to Wikidata and query data using SPARQL. Let’s approach them one by one. The first function to implement is `findAttractions` :
Please read the following pages without trying to repeat only the code marked with `">"` . There are some big Wikidata queries ahead. You will be able to import final implementations into your REPL with a single command (if you use the book’s code repository).
```sql
def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]
```
We need to solve three problems before implementing it:
1. What SPARQL query will implement it?
2. How can we connect to and query the Wikidata API?
3. How can we transform the raw response to the `List[Attraction]` value?
1\. Creating the SPARQL query
Let’s start with the query itself. We want to find tourist attractions that contain the given name and can be ordered by name or population. Wikidata offers a service where we can test our queries live. Let’s go to **Wikidata Query Service** and try to implement such a query.
Since the SPARQL queries we use are pretty big, we won’t show their complete versions in the book. Please refer to the book’s companion source code if you want to learn more.

(You can visit this page by going to [https://query.wikidata.org](https://query.wikidata.org) . There are examples that’ll get you started.)
2\. Connecting to and querying the Wikidata service
Now that we know what query we want to use, we need a way to send this query to the Wikidata server:
- We need the address of the server.
- We need to understand the preferred format of request and response.
There are multiple ways we could approach this task. The address of the server is pretty straightforward. We are going to use the [https://query.wikidata.org/sparql](https://query.wikidata.org/sparql) endpoint. In terms of format we could try to implement both the networking and query formatting ourselves or use an existing library. There are multiple choices, and you probably think that if we want to follow the functional way, our choices are very limited. Truth being told, there are some options out there that expose more functional APIs than others—they use immutable values and pure functions and expose `IO` values. You already know how to use such APIs. What you may not know is that **your choice is not really limited to them!** If there is a popular, well-established client library that you’d like to use, but its nature is imperative, you can still incorporate it in your functional program! This is what we are going to show in this chapter. The imperative, Java-based client library for connecting and querying the Wikidata server is **Apache Jena** —“a free and open source Java framework for building Semantic Web and Linked Data applications.” Here’s a simple query written in **imperative Java** :
THIS IS BIG!
`IO` enables you to use well-established imperative client libraries in your functional programs!
We are showing imperative Java here because that’s what you usually see in documentation or tutorials introducing the library you want to use.
```sparql
String query = "PREFIX wd:
\n" + ①
"PREFIX wdt:
\n" +
"PREFIX rdfs:
\n" +
"SELECT DISTINCT ?attraction ?label WHERE {\n" +
" ?attraction wdt:P31 wd:Q570116;\n" +
" rdfs:label ?label.\n" +
" FILTER(LANG(?label) = \"en\").\n" +
"} LIMIT 3";
RDFConnection connection = RDFConnectionRemote.create() ②
.destination("https://query.wikidata.org/")
.queryEndpoint("sparql")
.build();
QueryExecution execution = connection.query(QueryFactory.create(query));
Iterator solutions = execution.execSelect(); ③
// TODO: parse and use solutions
execution.close(); ④
connection.close();
```
① A query that finds three tourist attractions (you can input this query into [Wikidata Query Service](https://query.wikidata.org/) and see results for yourself)!
② We create a connection to the Wikidata server. `RDFConnection` , `QueryExecution` , and `QuerySolution` are Apache Jena types.
③ Here, we get results as an `Iterator` , which only enables you to lazily process one item at a time. This is the place we need to use this data in our application (see the next page for details).
④ We need to close both a query execution context and the connection, because they are holding some side-effectful resources as their state. In Java, the best approach would be to use the try-with-resources clause.
3\. Extracting and parsing the query results
The last problem we need to solve is how to extract the results from Apache Jena’s `Iterator` into something usable. Let’s focus on extracting the `String` s first because we already know how to work with them in the functional context.
```sql
String query = ... + "SELECT DISTINCT ?attraction ?label WHERE {\n" + ...;
RDFConnection connection = ...;
QueryExecution execution = ...;
Iterator solutions = execution.execSelect();
solutions.forEachRemaining(solution -> {
String id = solution.getResource("attraction").getLocalName();
String label = solution.getLiteral("label").getString();
System.out.printf("Got attraction %s (id = %s)%n", label, id);
});
execution.close();
connection.close();
```
Here, we get results as an `Iterator` . Then, we print an attraction id and label for each “row." Note that both attraction and label were part of the SELECT clause in our SPARQL query.
When we run this piece of code, we should see exactly three tourist attractions printed to the console—and since we haven’t provided any ordering mechanism, there will be some differences in which attractions are returned. In one of my executions I got the following:
Note that all the samples we show, including imperative Java examples, can be found in the book’s companion source code. They are packaged in executable classes.
```
Got attraction Cappadocia (id = Q217265)
Got attraction Great Geysir (id = Q216846)
Got attraction Yellowstone National Park (id = Q351)
```
This is all we need to understand how to query Wikidata using the imperative Apache Jena library. There is a lot of side-effectful, **unsafe code that can’t be used directly in pure functions** . Even the `getResource` and `getLiteral` calls above **can produce exceptions** ! So until we have our hands on immutable values, like `String` s, we need to wrap the imperative library code in `IO` values to be able to safely use it in our functional programs. Additionally, we have a new problem of resource handling (opening and closing connections, even in the presence of a failure), which we’ll also need to handle using `IO` to be on the safe side.
We will use the library directly in our functional codebase by wrapping its functionalities directly in `IO` . We will show you how to do it and allow to import it directly into your REPL for further use.
This is just an example, but note that all three problems we described—creating a query, connection to a server, and parsing a response—apply to many other existing use cases, for example, database queries. The point here is that you can use existing well-known imperative libraries, but you need to wrap the unsafe code as `IO` values yourself. They need to describe side-effectful programs, which, when executed, produce immutable values. Next, we’ll show how to do it.
## Following the design
Now that we know how to query Wikidata, we can now go back to our functional program and try to integrate our findings into it. The design so far has been done in three steps: we created the data model using provided requirements, then we sketched the signatures of three pure functions that we want to use as input actions (and bundled them together as a `DataAccess` type), and finally, we drafted the first version of the business logic as the `travelGuide` function.

We also learned how to use Apache Jena to query Wikidata. The next step should be pretty obvious: **we need to implement the three functions defined inside** `DataAccess` **, so they use Apache Jena internally** . Note how we first defined `DataAccess` and chose the library just now! We made this decision as late as possible. However, the main objective is still not achieved: we still need to make the whole thing work.
Let’s think about it first. How would you approach implementing the findAttractions function using Apache Jena? How do we make sure the functional core doesn’t know anything about what library is used internally to query data? | |
## Implementing input actions as `IO` values
Let’s try to implement `findAttractions` using Apache Jena and the Wikidata server. This example should also show you what kinds of problems you are going to encounter when trying to write an IO-heavy functional application.
As always, we can approach this problem from the top (starting with the signature) or from the bottom (figuring out smaller pieces before using them in the final function implementation). Since we have already defined the three smaller problems, it would be wise to solve them individually. That’s why the bottom-up approach is what we’ll use here.
Connecting to the server
Creating Apache Jena’s `RDFConnection` value is side-effectful and unsafe. That’s why we need to wrap it inside an `IO` value:
You need to `import org.apache.jena.query._` and `org.apache.jena.rdfconnection._` to use the library types. The book’s `sbt console` session imports them automatically.
> | val getConnection: ① RDFConnectionRemote.create
.destination("https://query.wikidata.org/")
.queryEndpoint("sparql")
.build
)① RDFConnection is the type coming from the external library. It’s imperative and potentially side-effectful, so we wrap it in an IO . The same will happen with other library types (e.g., QueryFactory and QueryFactory below). |
Creating the query and executing it
A query is just a `String` value, so we don’t need anything more here. We also need to support an `AttractionOrdering` argument. We can “transform” it into a `String` value using pattern matching and then use the resulting `String` value inside the `query` final value.
```sql
val orderBy = ordering match {
case ByName => "?attractionLabel"
case ByLocationPopulation => "DESC(?population)"
}
val query = s"""... SELECT DISTINCT ?attraction ?attractionLabel ①
?description ?location ?locationLabel ?population WHERE {
...
} ORDER BY $orderBy LIMIT $limit"""
```
① Many languages have advanced features that allow you to create more complicated `String` values. The features we use here are string interpolation (embedding a smaller `String` value inside a bigger one using a name) and multi-line string values. In Scala, string interpolation is achieved using the `s` prefix and `$name` , while multi-line strings are defined using triple quotes.
> | def execQuery(getConnection: IO[RDFConnection], query: String): IO[List[QuerySolution]] = {
getConnection.flatMap(c => IO.delay(
asScala(c.query(QueryFactory.create(query)).execSelect()).toList
))
}① We flatMap the getConnection value with a function that uses this connection and returns another IO value that describes how the connection is used to send the query to the server and return an Iterator back, which is transformed into an immutable value using asScala . |
Parsing the results
If our query is successful , we will get a `List` of `QuerySolution` s back. These are not immutable values, so we need to be very careful when dealing with them. The best way is to wrap every usage of a `QuerySolution` in `IO.delay` . This way we will get a description back, which we can pass around and handle functionally. Note that the signature helps to understand what is going on inside. You need to pass a `QuerySolution` , and you will get a description of a program that produces our immutable `Attraction` when executed successfully. Let’s first recap how the model looks.
Note that even though the `List` is immutable, its elements are imperative mutable types, which we still need to handle before calling it a day.
```
opaque type LocationId = String
case class Location(id: LocationId, name: String, population: Long)
case class Attraction(name: String, description: Option[String], location: Location)
```
And here’s how we can safely produce an `IO[Attraction]` from an existing impure `QuerySolution` .
> | def parseAttraction(s: QuerySolution): IO[Attraction] = { IO.delay(
Attraction(
name = s.getLiteral("attractionLabel").getString,
description =
if (s.contains("description"))
Some(s.getLiteral("description").getString)
else None,
location = Location(
id = LocationId(s.getResource("location").getLocalName),
name = s.getLiteral("locationLabel").getString,
population = s.getLiteral("population").getInt
)
)
)
} |
Note how we use named parameters here to make the code more readable. This code creates the `Attraction` value using some unsafe calls to the provided `QuerySolution` (named `s` ). The unsafe calls that can throw exceptions are highlighted. Note that `QuerySolution` is specific to the Apache Jena library. You need to be aware which calls are unsafe when integrating with another one. Such calls should be wrapped in `IO` .
The gray area between the functional core and impure code The function above is not a pure function even though it uses IO . It’s not pure because it operates on values that are not immutable. We need to be very careful when writing and using it. It should be separated from other, especially functional modules (no pure function can directly use parseAttraction ) and used privately inside a function with a wider IO context without being exposed anywhere. This extra care we need to take is the cost of using imperative client libraries. You won’t have such problems if you choose functional libraries to fetch data from databases and other APIs. They expose pure functions only, which you’ve already learned to use. There are also languages, like Haskell, that only offer purely functional libraries. | Functional core Design principles of integrating pure and impure code in a program were discussed in chapter 8. We chose Apache Jena to show you that your options are not limited to only purely functional libraries. You can use anything with some caution. |
## Separating the library `IO` from other concerns
Let’s put it all together in a single implementation of our input actions defined in the `DataAccess` type. We have defined one value and two helper functions that we will be able to reuse. Here are their signatures:
```sql
val getConnection: IO[RDFConnection]
def execQuery(getConnection: IO[RDFConnection], query: String): IO[List[QuerySolution]]
def parseAttraction(s: QuerySolution): IO[Attraction]
def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]] = {
val orderBy = ordering match {
case ByName => "?attractionLabel"
case ByLocationPopulation => "DESC(?population)"
}
val query = s"""... SELECT DISTINCT ?attraction ?attractionLabel
?description ?location ?locationLabel ?population WHERE {
...
} ORDER BY $orderBy LIMIT $limit"""
for {
solutions <- execQuery(getConnection, query)
attractions <- solutions.traverse(parseAttraction) // or map(parseAttraction).sequence
} yield attractions
}
```
We could implement the other two functions defined in the DataAccess type in a similar manner. However, there are several problems with this approach, and since we are trying to get something to work, we will just focus on the most critical one now. The getConnection value describes a program that creates a connection when executed. That means we will create a connection every time we want to query the server! Additionally, we don’t have any chance to close connections. That’s something that needs to be addressed right away because it affects a lot of places, and it couldn’t possibly be used in any real-world program. But there is a design trick we can use here—namely, making it someone else’s problem * , which may just be a specific case of making decisions as late as possible. Instead of figuring out how to handle closeable resources functionally (there is a very clean solution to this problem, which we will show later), we can just require something different to be passed to our function. We have a very powerful functional technique at our disposal: passing functions as parameters ! | Functions as parameters We discussed passing functions, (which are just values) as parameters and currying in chapter 4. * It’s still a helpful trick, even if by “someone else" we mean “us in the future." |
## Currying and inversion of control
Whenever you need to deal with a problem of too many responsibilities or too complex flows that are not directly related to the main responsibility of the function you implement, it means it’s a more of an accidental concern. The best course of action is to introduce a new parameter and “outsource” this particular concern to the user of your function.
In our case, we tried to implement a function that gets some input parameters and returns an `IO[List[Attraction]]` program that queries the real Wikidata server.
THIS IS BIG!
“Outsourcing” a concern by requiring a new parameter is a very common design practice in FP.
```sql
val getConnection: IO[RDFConnection] ①
def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]] = {
...
for {
solutions <- execQuery(getConnection, query) ②
attractions <- solutions.traverse(parseAttraction)
} yield attractions
}
```
① `getConnection` is just a value that creates and returns a new connection every time it’s executed.
② We open a new connection every time this program is executed. Additionally, we are required to close this connection, which we forgot to do here. If a design requires us to remember to do something not strictly related to the business logic, it means it’s not a good design.
Passing a connection
The first idea would be to pass the connection as a parameter. def findAttractions(connection: RDFConnection) (name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]We provide it in a separate parameter list (we say that the function is curried) because this parameter is not related to the essential concern. We use currying to be able to “configure” functions by providing only some parameters (like connection ) to get a fully working version and pass it to modules that don’t want to know anything about a connection. Here’s how it could look in action: | Inversion of control We discussed inversion of control in a slightly different context in chapter 9. |
```
findAttractions(connection) ①
→ (String, AttractionOrdering, Int) => IO[List[Attraction]]
```
① The caller of `findAttractions` needs to provide a connection to get a “configured" function that will be able to query attractions.
That means that the caller of `findAttractions` needs to worry about creating and closing connections, not us.
However, as discussed earlier, `RDFConnection` is not an immutable value, and we should refrain from using it directly whenever we can. Passing an `IO[RDFConnection]` is not ideal as well because we are not able to reuse a single connection in many queries. `IO` is just a description of a program that creates a new connection, so executing it will always create a new connection. That’s not a sustainable solution.
## Functions as values
It may feel like we are going round in circles thinking about all the problems with passing and handling connections. This feeling should trigger an urge to outsource even more. Let’s think about what we really need in `findAttractions` and other API input (data access) functions.
Passing a “querying behavior”
We don’t need a connection. We need a way to execute a query. We have a query String and want a List of QuerySolution s that we know how to parse. Does that sound familiar to you? We have just defined a function we need. And there is no mention about any connection-specific things, too! | |
```sql
def findAttractions(execQuery: String => IO[List[QuerySolution]])
(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]
```
Now, we can just expect the querying behavior from the caller. This means that the caller now has more responsibilities, and that was the whole point of this refactoring. We pushed the responsibility upwards. There will be a module somewhere in our program that will be more competent in handling connections and creating proper `String => IO[List[QuerySolution]]` functions to pass downwards.
Configuring a bag of functions
There is one outstanding issue. We have already defined the `DataAccess` type and stated exactly which three functions need to be implemented.
```sql
trait DataAccess {
def findAttractions(name: String, ordering: AttractionOrdering,
limit: Int): IO[List[Attraction]]
def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]] ①
def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]] ②
}
```
① Proper implementations of all `DataAccess` functions can be found in the book’s repository. The implementations are all similar to what we showed with `findAttractions` .
② You can create a `DataAccess` value by using the `new` keyword and providing all required implementations.
There is no place for any additional parameter. These signatures don’t assume anything about the internal querying mechanism, and since they are used inside the functional core, we need to keep it this way. We need a different function that returns a specific `DataAccess` implementation!

\* You can create a `DataAccess` value by using the `new` keyword and providing all required implementations.
## Connecting the dots
We now have all the building blocks we need to run a first, fully working version of the travel guide application! Try it yourself!
If you haven’t followed along, run `sbt console` now, and execute code marked with `“>"` from this page only.


## We made it work
We pushed the design as much as we could to get a working version. It’s time to focus on making sure all the requirements are met.
Requirements: Pop culture travel guide
1. The application should take a single **`String`** value: a search term for the tourist attraction that the user wants to visit and needs a travel guide for.
2. The application needs to search for a given attraction, its description (if it exists), and its geographical location. It should prefer locations with larger populations.
3. The application should use a location to do as follows:
- Find artists originating from this location, sorted by the number of social media followers
- Find movies that take place in this location, sorted by the box office earnings
4. For a given tourist attraction, artists and movies form its “pop culture travel guide” that should be returned to the user. If there are more possible guides, the application needs to return the one with the highest score, which is calculated as follows:
- 30 points for a description
- 10 points for each artist or movie (max. 40 points)
- 1 point for each 100,000 followers (all artists combined; max. 15 points)
- 1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points)
5. We will add support for more pop culture subjects in the future (e.g., video games).
Since we already designed the blueprint of the application and separated the data access concern and its internals, we can safely focus on our business logic and iteratively make it better.
**Version 1** The first version of travelGuide we implemented earlier
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 1)
guide <- attractions.headOption match {
case None => IO.pure(None)
case Some(attraction) =>
for {
artists <- data.findArtistsFromLocation(attraction.location.id, 2)
movies <- data.findMoviesAboutLocation(attraction.location.id, 2)
} yield Some(TravelGuide(attraction, artists.appendedAll(movies)))
}
} yield guide
}
```
In the current version of `travelGuide` , we just look at a single attraction returned by the `findAttractions` program. However, as we see above, there may be more attractions and we need to look at more than one, score them using the provided algorithm, and return the one with the highest score.
Let’s think about it first. What would be the next step, in your opinion? What change do we need to introduce? Is there a need for a new pure function? | |
## Making it right
The natural next step is to query more attractions, apply the scoring algorithm to them, and return the one with the highest score.
❶ | The scoring algorithm defined in the requirements can easily be implemented as a pure function. It should get a TravelGuide and return its score: |
```java
def guideScore(guide: TravelGuide): Int = {
val descriptionScore = guide.attraction.description.map(_ => 30).getOrElse(0)
val quantityScore = Math.min(40, guide.subjects.size * 10) ①
val totalFollowers = guide.subjects
.map(_ match {
case Artist(_, followers) => followers
case _ => 0
})
.sum
val totalBoxOffice = guide.subjects
.map(_ match {
case Movie(_, boxOffice) => boxOffice
case _ => 0
})
.sum
val followersScore = Math.min(15, totalFollowers / 100_000) ②
val boxOfficeScore = Math.min(15, totalBoxOffice / 10_000_000) ②
descriptionScore + quantityScore + followersScore + boxOfficeScore
}
```
① We count 30 points if there is a description and 0 if there’s not. Then, we add 10 points for each pop culture subject (max 40).
② We use pattern matching to destructure `subjects` and calculate the sum of followers. Then we use the same technique to sum the box office.
❷ | Now we can change the travelGuide function to use the guideScore function internally: |
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 3)
guides <- attractions
.map(attraction <-
for {
artists <- data.findArtistsFromLocation(attraction.location.id, 2)
movies <- data.findMoviesAboutLocation(attraction.location.id, 2)
} yield TravelGuide(attraction, artists.appendedAll(movies))
)
.sequence
} yield guides.sortBy(guideScore).reverse.headOption ①
}
```
① We map each attraction to an `IO` value describing a program that fetches artists and movies for the attraction’s location. We use sequence to transform a List\[IO\[TravelGuide\] into an `IO[List[TravelGuide]]` and sort the internal list using the `guideScore function` . We return a guide with the highest score, if there is any, or `None` otherwise.
We now have a better version that returns the best guide!
Quick exercise
Assuming we execute this new version of the travelGuide function with the Wikidata DataAccess and provide an attractionName for which there are at least three attractions in Wikidata, how many Wikidata server queries will there be in total? | Answer: maximum seven queries in total. |
## Resource leaks
The current version of the travelGuide function will make seven data queries if there are at least three attractions with a given name. When you try to run it for "Yosemite" , you can get various results. That’s because we have accidentally introduced a bug into our application: a resource leak ! | |
This leak is not present in the functional core because we only have immutable values and pure functions there. The usual suspect for such things is code outside of the functional core—usually, the impure code that connects all the modules together (i.e., the main process).

Such things may happen in other cases as well. For example, if you implement a web client and forget to read the whole HTTP response, you may end up with a similar leak, depending on the library you use. You need to understand what resources your programs need to acquire no matter what programming paradigm your team prefers.
It is a problem related to our library, but you can encounter it in many other libraries that come with their own connection pool tools or other resource management tools. It’s a universal problem, and we will provide a universal FP solution.
When you deal with impure, stateful values (objects) that additionally acquire and consume some resources, such as filesystem or network connections, you need to be very careful and always release those resources when you no longer need them. That’s usually very hard to achieve in the presence of several possible program flows and error cases. That’s why many languages introduce special syntax that deals with resource handling and provides ways to always release them. Java has `try-with-resources` , and some FP languages have the `Resource` type. Before we learn about it, let’s figure out the problem using only `IO` .
## Handling resources
We are able to handle releasable resources using the knowledge we’ve gained so far (i.e., using the `IO` type alone).
> | def createExecution(connection: RDFConnection, query: String): IO[QueryExecution] = IO.blocking(connection.query(QueryFactory.create(query))) ①
def closeExecution(execution: QueryExecution): IO[Unit] =
IO.blocking(execution.close())
def execQuery(connection: RDFConnection)(query: String): IO[List[QuerySolution]] = {
for {
execution <- createExecution(connection, query)
solutions <- IO.blocking(asScala(execution.execSelect()).toList)
_ <- closeExecution(execution) ②
} yield solutions
}① As a reminder, IO.blocking does the same thing as IO.delay and has the same API. The difference is that the delayed action is executed on a thread pool that is better suited for blocking operations. ② We are running the closeExecution program after we get solutions . However, if a query fails we are still not covered. We may need to use orElse for that. |
It may work, but it doesn’t feel very declarative. It also is prone to human error: we already learned the hard way that it’s very easy to forget to release something. We’d like to use more of the functional programming power here. Fortunately, there is something more declarative and more descriptive—something that always releases the resource no matter what happens. Meet the `Resource` type!
If you don’t use the book’s `sbt console` , please `import cats.effect.Resource` .

For example, since `QueryExecution` is something that needs to be acquired and released, **we can represent this fact as a** `Resource` **value** :
```
def execQuery(connection: RDFConnection)(query: String): IO[List[QuerySolution]] = {
val executionResource: Resource[IO, QueryExecution] =
Resource.make(createExecution(connection, query))(closeExecution)
???
}
```
Note: We reused functions defined at the beginning of this page and passed them as the `acquire` and `release` functions .
We now have a `Resource[IO, QueryExecution]` value, but what’s next?
## Using a `Resource` value
How does the `Resource` value help? Let’s write a different version of the `execQuery` function and see what it gives us.
> | def execQuery(connection: RDFConnection)(query: String): IO[List[QuerySolution]] = { val executionResource: Resource[IO, QueryExecution] =
Resource.make(createExecution(connection, query))(closeExecution)
executionResource.use(execution => IO.blocking(asScala(execution.execSelect()).toList))
} |
Not much changed at first sight. But this function is a lot safer than anything we’ve written before! A `Resource` value has a **`use`** function defined on it, which takes another function from a value representing the acquired resource to a program that needs to be executed. Note that the function will be called internally after the resource is acquired (using the function we provided when we created this `Resource` value). If anything goes wrong (a failure), the resource will be released. If the program provided in `use` finishes successfully, the resource will also be released (using the function we provided when we created this `Resource` value). **This way we can focus on using the resource without worrying about acquiring and releasing it!** And the best news is that it’s all modeled as immutable values!

Now, we can model the connection as `Resource` , too:

## We made it right
It turned out our initial design was quite good. We needed to fix some issues regarding missing requirements (sorting travel guides) and resource handling. We learned about the `Resource` type along the way.
THIS IS BIG!
We model releasable resources as values.


**One more thing!** `Resource` has `map` and `flatMap` functions! That means we can make the main application process even better.
> | val dataAccessResource: ① connectionResource.map(connection => getSparqlDataAccess(execQuery(connection)))
dataAccessResource.use(dataAccess => travelGuide(dataAccess, "Yosemite")).unsafeRunSync() ① See the book’s source code for more about Resource ! |
## Coffee break: Make it fast 
The current implementation of `travelGuide` makes several queries to choose and return the best possible guide. However, all of these queries are done sequentially. Taking into account that each of them may take even one second, that’s not going to be a very fast application.
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 3)
guides <- attractions
.map(attraction =>=>
for {
artists <- data.findArtistsFromLocation(attraction.location.id, 2)
movies <- data.findMoviesAboutLocation(attraction.location.id, 2)
} yield TravelGuide(attraction, artists.appendedAll(movies))
)
.sequence
} yield guides.sortBy(guideScore).reverse.headOption
}
```
Your task is to refactor the function so it uses concurrency as much as possible . Specifically, queries for each attraction are independent of each other and can be run in parallel. Similarly, finding artists and movies for a given attraction are two independent queries and can be run in parallel, too. When you think about the solution, please note that the change from a sequential to a multithreaded application is completely contained within one pure function that returns an immutable value. That’s the power of functional programming and functional design! | 1 |
Your second task is to look at the current design and solution from the bird’s-eye perspective. What are other things we could do to make it faster? How often does the same query return a different answer? Maybe we could reuse that fact to make the following program faster? connectionResource.use(connection => { val dataAccess = getSparqlDataAccess(execQuery(connection))
for {
result1 <- travelGuide(dataAccess, "Yellowstone")
result2 <- travelGuide(dataAccess, "Yellowstone")
result3 <- travelGuide(dataAccess, "Yellowstone")
} yield result1.toList.appendedAll(result2).appendedAll(result3)
}) | 2 The second task is harder than the first, but you already have all the knowledge and tools at your disposal to solve it! |
Hints
- We use `sequence` in the current version. Do you remember **`parSequence`** ?
- We may need caching to make it even faster when more guides are searched for. \*
\* Remember `Ref` values from chapter 10? Maybe you could use them to cache query results?
## Coffee break explained: Make it fast 
Making concurrent queries is just a matter of replacing sequence and flatMap calls with parSequence . Since fetching artists and movies is independent, we don’t really need to do them in sequence. That’s why we need to replace the for comprehension with a List . | 1 |
```
def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] = {
for {
attractions <- data.findAttractions(attractionName, ByLocationPopulation, 3)
guides <- attractions
.map(attraction =>
List(
data.findArtistsFromLocation(attraction.location.id, 2),
data.findMoviesAboutLocation(attraction.location.id, 2)
).parSequence
.map(_.flatten)
.map(popCultureSubjects => TravelGuide(attraction, popCultureSubjects))
).parSequence
} yield guides.sortBy(guideScore).reverse.headOption
}
```
We `map` each attraction to a program. Programs for all attractions are run concurrently (the second `parSequence` ). Inside each attraction’s program there are two other programs that are run concurrently (the first `parSequence` ): one for artists and one for movies. Since the first program’s result is a `List[Artist]` , and the second’s is a `List[Movie]` , we end up with a `List` of two `Lists` , and the resulting type is `List[List[PopCultureSubject]]` (because `Movie` and `Artist` are both PopCultureSubjects).We flatten them and use them, name the resulting list `popCultureSubjects` , and put it inside a new `TravelGuide` .
We can make it even faster by noticing that our queries usually return the same results (locations of artists or movies don’t change very often), so we can heavily cache them. It turns out that our design and its separated concerns allow us to introduce cache by passing a different function to getSparqlDataAccess ! (Yes, that’s all we need!) | 2 |
```sql
def cachedExecQuery(connection: RDFConnection, cache: Ref[IO, Map[String, List[QuerySolution]]])(
query: String
): IO[List[QuerySolution]] = {
for {
cachedQueries <- cache.get
solutions <- cachedQueries.get(query) match {
case Some(cachedSolutions) => IO.pure(cachedSolutions)
case None =>
for {
realSolutions <- execQuery(connection)(query)
_ <- cache.update(_.updated(query, realSolutions))
} yield realSolutions
}
} yield solutions
}
```
Our function first gets a program that, when executed, will read the current value of the cache and then will get query results for the given query. If they are not present, we fire up the old `execQuery` function, store the solutions in cache, and return them.
## Summary
In this chapter we used multiple tools and techniques from earlier parts to create a real-world application that fetches data from Wikidata.
CODE: `CH11_*`
Explore this chapter’s source code by looking at `ch11_*` files in the book’s repository.
Design real-world functional applications
We used the _functional core_ design concept, which contains only pure functions and immutable values that are used by external modules like the main application process, which “configures” pure functions with specific input and output actions.
Model more complicated requirements as types
The design process started with requirements. We transformed them into a data model and pushed toward a working solution in the spirit of “make it work, make it right, make it fast.”
Integrate with real data-source APIs using IO
We modeled the data access layer as a bag of three pure functions, which we called `DataAccess` . Only after implementing the first version of the business logic (the `travelGuide` function) did we start wondering about the specifics of the service that would become our data provider. We chose Wikidata, which is a free service exposing a SPARQL endpoint.
We used SPARQL for queries, but the techniques we showed can also be used in other places, such as SQL servers and queries.
We used the Apache Jena library to connect and query the Wikidata server. We showed that, even though it’s an imperative library, we have tools at our disposal to integrate with it without changing any of the pure functions and immutable values we had already put in place.
Avoid resource leaks
Internally, the data access layer implemented using the imperative Apache Jena library keeps its own connection pool and query execution contexts. These are stateful resources that need to be acquired (e.g., creating a connection to a server) and released when no longer needed, even in the presence of errors. Not releasing such resources leads to resource leaks. We learned that we can easily manage such cases without any headaches using `Resource` values, which describe releasable resources.
There are more cases of resources we can manage using a `Resource` value. You can model your application’s internal resources in this way as well!
There’s more! Have a look at the source code in the book repository to see some additional improvements, including IO timeout support!
Cache query results to speed up the execution
Finally, we tried to make the application fast. We used some concurrency and implemented a query results cache by changing just a single small dependency, which proved that the design is very robust.