In our previous chapter, we dealt with many functional programming techniques. In this chapter we are going to see yet another important concept in programming called error handling. Error handling is a common programming technique for handling errors in your application. The functional programming method of error handling will be different, though, and that’s exactly what we are going to see in this chapter.
We will be looking at a new concept called functor. This new friend is going to help us handle errors in a purely functional way. Once we grasp the idea of a functor, we are going to implement two real-world functors: MayBe and Either . Let’s get started.
Note
The chapter examples and library source code are in branch chap08. The repo’s URL is https://github.com/antsmartian/functional-es8.git .
Once you check out the code, please check out branch chap08:
...
git checkout -b chap08 origin/chap08
...
For running the codes, as before run:
...
npm run playground
...
What Is a Functor?
A functor is a plain object (or type class in other languages) that implements the function map that, while running over each value in the object, produces a new object.
It is not that easy to understand the definition at first sight. We are going to break it down step by step so that we clearly understand it and see in action (via writing code) what a functor is.
Functor Is a Container
Container Definition
Note
You might be wondering why we didn’t write the Container function using our arrow syntax:
const Container = (val) => {
this.value = val;
}
That code will be fine, but the moment we try to apply the new keyword on our Container, we will get an error like this:
Container is not a constructor(...)(anonymous function)
Why is that? Well, technically, to create a new Object, the function should have the internal method [[Construct]] and the property prototype. Sadly, the Arrow function doesn’t have both! So here we are falling back to our old friend function, which has the internal method [[Construct]], and it also has access to the prototype property.
Playing With Container
of Method Definition
Creating Container with of
Now that we have defined that the functor is nothing but a Container that can hold the value, let’s revisit the definition of a functor.
Functor is a plain object (or type class in other languages) that implements the function map while running over each value in the object to produce a new object.
It looks like functor needs to implement a method called map. Let’s implement that method in the next section.
Implementing map
Before we implement the map function, let’s pause here and think about why we need the map function in the first place. Remember that we created Container that just holds the value we pass into it. Holding the value hardly has any use, though, and that is where the map function comes into place. The map function allows us to call any function on the value that is being currently held by the Container.

Mechanism of Container and map function
map Function Definition
Functor is a plain object (or type class in other languages) that implements the function map that, while running over each value in the object, produces a new object.
Functor is an object that implements a map contract.
Now that we have defined it, you might be wondering what functor is useful for. We are going to answer that in the next section.
Note
Functor is a concept that looks for a contract. The contract as we have seen is simple, implementing map. The way in which we implement the map function provides different types of functor like MayBe and Either, which we are going to discuss later in this chapter.
MayBe
We started the chapter with the argument of how we handle errors and exception using functional programming techniques. In the previous section we learned about the fundamental concept of functor. In this section, we are going to see a type of functor called MayBe. The MayBe functor allows us to handle errors in our code in a more functional way.
Implementing MayBe
MayBe Function Definition
MayBe’s map Function Definition
Now it’s time to see MayBe in action.
Simple Use Cases
Creating our First MayBe
Now our code doesn’t explode in null or undefined values as we have wrapped our value in the type safety container MayBe. We are now handling the null values in a declarative way.
Note
On MayBe.of(null) case, if we call the map function, from our implementation we know that map first checks if the value is null or undefined by calling isNothing:
//implementation of map
MayBe.prototype.map = function(fn) {
return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this.value));
};
if isNothing returns true. We return back MayBe.of(null) instead of calling the passed function.
Chaining with map
as expected.
the second map will be called always (i.e., the chained maps to any level will be called always); it is just that the next map function in the chain returns undefined (as the previous map returns undefined/null), without applying the passed function. This process is repeated until the last map function call is evaluated in the chain.
Real-World Use Cases
Getting Top 10 SubReddit Posts
Note
request comes from the package sync-request. This will allow us to fire a request and get the response in synchronous fashion. This is just for illustration; we don’t recommend using synchronous calls in production.
From the response we need to return the array of JSON object that has the URL and title in it. Remember that if we pass an invalid subreddit type such as test to our getTopTenSubRedditPosts, it will return an error response that does not have a data or children property.
Getting Top 10 SubReddit Posts Using MayBe
Note
The response might not be the same for the readers, as the response will change from time to time.
without throwing any error. Even though our map function tries to get the data from the response (which is not present in this case), it returns MayBe.of(null) , so the corresponding maps would not apply the passed function, as we discussed earlier.
We can clearly sense how MayBe handled all the undefined/null errors with ease. Our getTopTenSubRedditData looks so declarative.
That’s all about the MayBe Functor. We are going to meet another functor in the next section called Either.
Either Functor
as we would expect. However, the question is which branching (i.e., out of two earlier map calls) failed with undefined or null values. We cannot answer this question easily with MayBe. The only way is to manually dig into the branching of MayBe and discover the culprit. This doesn’t mean that MayBe has flaws, but just that in certain use cases, we need a better functor than MayBe (mostly where you have many nested maps). This is where Either comes into the picture.
Implementing Either
Either Functor Parts Definition
Either Definition
You might be wondering what the usefulness of Some or Nothing are. To understand this, let’s revisit our Reddit example version of MayBe.
Reddit Example Either Version
Get Top Ten Subreddit Using Either
Get Top Ten Subreddit Using Either
This code is just literally the MayBe version, but it’s just not using MayBe; rather it’s using Either’s type.
This is so brilliant. Now with Either types in place, we get back the exact reason why our branching failed. As you can guess, getTopTenSubRedditPostsEither returns Nothing in case of an error (i.e., unknown Reddit type); hence the mappings on getTopTenSubRedditDataEither will never happen because it is of type Nothing. You can sense how Nothing helped us in preserving the error message and also blocking the functions to map over.
That’s all about Either .
Note
If you are from a Java background, you can sense that Either is very similar to Optional in Java 8. In fact, Optional is a functor.
Word of Caution: Pointed Functor
Before we close the chapter, we need to make a point clear. In the beginning of the chapter we started saying that we created the of method just to escape the new keyword in place for creating Container. We did the same for MayBe and Either as well. To recall, functor is just an interface that has a map contract. Pointed functor is a subset of functor, which has an interface that has an of contract.
What we have designed thus far is called a pointed functor. This is just to make the terms right in the book, but you got to see what problem functor or pointed functor solves for us in the real world, which is more important.
Summary
We started our chapter by asking questions about how we will be handling exceptions in the functional programming world. We began with creating a simple functor. We defined a functor as being nothing but a container with a map function implemented. Then we went ahead and implemented a functor called MayBe. We saw how MayBe helps us in avoiding pesky null/undefined checks. MayBe allowed us to write code in functional and declarative ways. Then we saw how Either helped us to preserve the error message while branching out. Either is just a supertype of Some and Nothing. Now we have seen functors in action.