A Functor is a simple type class that has just two functions, fmap and <$ . As you’ll see throughout the rest of this book, Functor instances are extremely common in Haskell, and you’re likely to work with this type class in nearly every program you write. Before we dive into what a Functor is, let’s take a look at how we could define the type class ourselves if it wasn’t already provided for us in base :
| | class Functor f where |
| | fmap :: (a -> b) -> f a -> f b |
| | (<$) :: a -> f b -> f a |
| | (<$) a fb = fmap (const a) fb |
In addition to the functions defined in the type class, the <$> function is also defined in the standard library as an infix version of fmap . In most Haskell code, you’ll see <$> being used at least as often as fmap , if not more so. Let’s go ahead and add it to our example code:
| | infixl 4 <$> |
| | (<$>) :: Functor f => (a -> b) -> f a -> f b |
| | (<$>) = fmap |
To understand what a Functor is, let’s start by looking at what it does . The fmap function is the important function to think about when we’re trying to understand Functor . Although (<$) is useful from time to time, it can be implemented in terms of fmap and understanding it doesn’t really bring us a lot closer to understanding what a functor is.
The type of fmap is:
| | fmap :: (a -> b) -> f a -> f b |
The type of fmap might look familiar; it’s very similar to the type of the map function that you’ve been using for some time now:
| | map :: (a -> b) -> [a] -> [b] |
This isn’t a coincidence at all! In fact, lists are functors and the definition of fmap for a list is just map .
What can this similarity between map and fmap start to tell us about Functor ? For one thing, it can help us start to understand that, just like map is about being able to work with the individual elements of a list without needing to be concerned about the overall shape or structure of the list, fmap gives us a way to work with values of anything that has a valid Functor instance without having to worry about whatever definition of structure is meaningful to the type we happen to be dealing with at the time.
Structure of Types
You can think of the structure of a value as its general “shape.” For example, if you think of a list, the number and order of its elements provide its shape. If we have a list of numbers, we can convert them to strings, or add five to all of them without changing the number or order of the arguments. Another name for pattern matching is “destructuring,” and you can use this to get an intuition about what structure means. When you could pattern match on something, for example, on a Maybe value, you’re often matching on the structure.
Another equivalent way of thinking about Functor is to think of values as representing a “computation” or a “program.” A value like [Int] is a computation that will generate several outputs, whereas Maybe Int is a computation that might not generate a value at all, and IO Int is a computation that will generate an Int but might also have some real-world side effects. In this view of the world, a Functor is a computation that allows us to change the type of result that it will generate by passing it a function.
The “structural” and “computational” views of Functor , as well as Applicative and Monad , are interchangeable. Whichever view of the problem you take, it won’t change the way you approach code. Picking one view or another can, however, make it a bit easier to figure out what code to write, since different problems might lend themselves better to one view or another. Generally, in this book we’ll prefer to take the structural view of things when we can, but throughout this chapter we’ll examine both the structural and computational meaning of the type classes we’re looking at so that you’ll be prepared no matter what sort of problem comes along.
So, now that we have a general understanding of what they are, let’s look at a couple of examples of creating instances of the Functor type class. We’ll start with our old friend Maybe . If we think about what it would mean to “map” over a Maybe , we could say that one reasonable definition would be to apply a function to a value if we have one. Let’s take a look at how we could write fmap for Maybe :
| | data Maybe a = Nothing | Just a |
| | instance Functor Maybe where |
| | fmap _ Nothing = Nothing |
| | fmap f ( Just a) = Just (f a) |
Our implementation of fmap lines up with our idea of what mapping means for a Maybe value. If we have Nothing then we just return Nothing , but if we have some value, then we apply our function to that value. If you load up ghci we can test this out (don’t worry about writing this code yourself, the standard library provides a Functor instance for Maybe for you already). In the following examples, we’ll use a mixture of both fmap and <$> so you can see how they each look when they are being used:
| | -- Show the value, if there is one |
| | λ show <$> Just 1 |
| | Just "1" |
| | |
| | -- Increment the value, if there is one |
| | λ (+1) <$> Just 1 |
| | Just 2 |
| | |
| | -- If there's a value, create a tuple of that value and its successor |
| | λ (\a -> (a, succ a)) <$> Just 9 |
| | Just (9, 10) |
| | |
| | -- If we try to increment the value inside of Nothing, we still get Nothing |
| | λ fmap (+1) Nothing |
| | Nothing |
| | |
| | -- Reverse the worder of words in a string, if we have one |
| | λ (unwords . reverse . words) <$> Just "hello, world" |
| | Just "world hello," |
| | |
| | -- Reversing the words in Nothing safely returns Nothing |
| | λ fmap (unwords . reverse . words) Nothing |
| | Nothing |
| | |
| | -- The <$ function replaces the value with a different value |
| | λ True <$ Just 4 |
| | Just True |
| | |
| | -- If we replace the value inside of Nothing, we still get nothing |
| | λ ("peanut butter", "jelly") <$ Nothing |
| | Nothing |
| | |
| | -- Even if we operate on a Nothing value, the types still change as expected |
| | λ let nothing = Nothing :: Maybe Int |
| | λ :type nothing |
| | nothing :: Maybe Int |
| | λ :type (True <$ Nothing) |
| | (True <$ Nothing) :: Maybe Bool |
Let’s look at another example of something that implements the Functor type class in a similar way: lists. The standard library provides an implementation of Functor for lists using map , but let’s write our own so that we can better get a feel for what’s happening. We’ll begin by creating a new list type, and adding a couple of utility functions to make it easier to work with:
| | data List a = Empty | List a ( List a) |
| | |
| | toList :: [a] -> List a |
| | toList [] = Empty |
| | toList (a:as) = List a (toList as) |
| | |
| | fromList :: List a -> [a] |
| | fromList Empty = [] |
| | fromList ( List a as) = a : fromList as |
The Functor instance for our list ends up looking quite a lot like the one we defined for Maybe . Calling fmap on an Empty list returns an Empty list, just like calling fmap on Nothing returns Nothing . When we have a non-empty list, we apply our function to the head of our list, and then fmap the rest of the list recursively. Let’s see what it looks like in code:
| | instance Functor List where |
| | fmap _ Empty = Empty |
| | fmap f ( List a as) = List (f a) (fmap f as) |
Like with our Maybe example, we’ll use the built-in standard library list and its Functor instance to visualize how this works in practice. Try it out with your own custom List type too.
| | -- map the successor function over all the elements in the list |
| | λ succ <$> [1..5] |
| | [2,3,4,5,6] |
| | |
| | -- map then show function over all the elements in the list |
| | λ show <$> [1..5] |
| | ["1","2","3","4","5"] |
| | |
| | -- replease every element in the list with True |
| | λ True <$ [1..5] |
| | [True,True,True,True,True] |
| | |
| | -- Replicate each element of the list 3 times |
| | λ replicate 3 <$> [1,2,3] |
| | [[1,1,1],[2,2,2],[3,3,3]] |
| | |
| | -- Replicate each element of the list and map the successor function to it |
| | λ (succ <$>) . replicate 3 <$> [1,2,3] |
| | [[2,2,2],[3,3,3],[4,4,4]] |
| | |
| | -- Replicate each element of the list and map the successor function to it |
| | -- then show the list |
| | λ show . (succ <$>) . replicate 3 <$> [1,2,3] |
| | ["[2,2,2]","[3,3,3]","[4,4,4]"] |
| | |
| | -- Replicate each element of the list and map a function that shows the the |
| | -- successor of it |
| | λ (show . succ <$>) . replicate 3 <$> [1,2,3] |
| | [["2","2","2"],["3","3","3"],["4","4","4"]] |
Another common type that has Functor instances is Either . As a reminder, we can write our own definition of Either this way:
| | data Either a b = Left a | Right b |
The instance for Either is a little bit different from what we’ve seen so far with Maybe and lists. Both of those types have a single type parameter, but Either has two type parameters. What does that mean for our Functor instance? It means that we can’t just go and create an instance of Functor directly, or we’ll get an error that looks something like this:
| | Either.hs:12:18: error: |
| | • Expecting one more argument to ‘Either’ |
| | Expected kind ‘* -> *’, but ‘Either’ has kind ‘* -> * -> *’ |
| | • In the first argument of ‘Functor’, namely ‘Either’ |
| | In the instance declaration for ‘Functor Either’ |
| | | |
| | 12 | instance Functor Either where |
| | | ^^^^^^ |
This error might look a bit weird at first, because it’s the first time we’ve run into a problem with Kinds . You can think of a Kind as “the type of a type.” Just like functions have different types if they take different numbers of parameters, a type will have a different Kind if it has a different number of type parameters.
We can look at the kind of a type in ghci using the :kind command. Let’s look at the kinds of a couple of types to understand what’s going on a bit better.
The kind of a normal type with no parameters, like an Int or a String is * :
| | λ :kind Int |
| | Int :: * |
| | |
| | λ :kind String |
| | String :: * |
The kind of a type that has been given all of its type parameters is also * . You’ll sometimes see types like this be referred to as fully saturated :
| | λ :kind Maybe Int |
| | Maybe Int :: * |
| | |
| | λ :kind [ String ] |
| | [ String ] :: * |
| | |
| | λ :kind Either String Int |
| | Either String Int :: * |
| | |
| | λ :kind ( Int -> Bool ) |
| | ( Int -> Bool ) :: * |
On the other hand, a type that still needs a type parameter will have the kind * -> * . You’ll notice that this looks a lot like the syntax we use for functions, and that’s a good intuition. We can think of types like this as functions that take a type as a parameter and return a type:
| | λ :kind Maybe |
| | Maybe :: * -> * |
| | |
| | λ :kind [] |
| | [] :: * -> * |
| | λ :kind Either String |
| | Either String :: * -> * |
| | |
| | λ :kind (forall a. a -> Int ) |
| | (forall a. a -> Int ) :: * |
And just like a function that takes two parameters will have a different type than a function that takes one parameter, a type constructor that takes two parameters will have a different kind than a type constructor that takes a single parameter. For example, let’s compare the kinds of Maybe , which take a single type parameter, to the kind of Either , which takes two type parameters:
| | λ :kind Maybe |
| | Maybe :: * -> * |
| | |
| | λ :kind Either |
| | Either :: * -> * -> * |
If we look at the type of fmap , we’re talking about a type that takes a single type parameter, and that means that its kind has to be * -> * .
| | fmap :: (a -> b) -> m a -> m b |
So, when we try to create an instance of Functor using Either , which has the kind * -> * -> * , the compiler will let us know that we can’t do that, because the kind of Either doesn’t match the kind that it was expecting.
So, what do we do? If we apply a type to Either then we’ll get a type with the kind that we need. Of course, we don’t want to pick any specific type, but we can use a type variable to allow anything for the first type parameter:
| | instance Functor ( Either a) where |
If we think back to the type of fmap , we had a type variable, m , that had the kind * -> * . In this case, we’re going to substitute m for Either a , so the type of fmap would be:
| | fmap :: (b -> c) -> ( Either a) b -> ( Either a) c |
The parentheses around (Either a) here are to illustrate how we’ve replaced m with Either a . Normally we’d write:
| | fmap :: (b -> c) -> Either a b -> Either a c |
So, applying a type variable lets us get the right kind, and create a Functor instance for Either . What, if anything, does this mean about how we will implement the instance?
In the case of Either , where the first type parameter corresponds to Left values, and the second type parameter corresponds to Right values, it means that fmap is only going to operate on Right values. Much like how fmap ignores Nothing values for Maybe , it will ignore Left values for Either a . Knowing that, our implementation is short and looks a lot like the instance we defined for Maybe :
| | instance Functor ( Either a) where |
| | fmap f ( Left a) = Left a |
| | fmap f ( Right a) = Right (f a) |
After all of this, you might find yourself asking, “What if we wanted to define a version of fmap that worked on Left values instead of Right ones?” Or more generally, “What if we want to define an instance on some type parameter other than the last one?”
Unfortunately, there’s not an easy way to handle this. When we’re working with functions and values, we have ways of easily applying a value to the second argument of a function; for type class instances we’re limited to applying types left-to-right in order.
If you do find yourself in a situation where you need to do this, generally the best approach is to use a newtype wrapper with the order of the type parameters reversed:
| | newtype ReverseEither a b = ReverseEither ( Either b a) |
| | deriving Show |
| | |
| | instance Functor ( ReverseEither a) where |
| | fmap f ( ReverseEither ( Left a)) = ReverseEither ( Left (f a)) |
| | fmap f ( ReverseEither ( Right a)) = ReverseEither ( Right a) |
Finally, before we move on to Applicative let’s look at one final example of a Functor that might not be quite so intuitive at first: functions. The normal everyday (->) style functions that we’ve been using since the very beginning of the book are another example of Functor s. We’ll implement our own version as an example shortly, but before we do, let’s use ghci to look at an example:
| | -- create a new function that we can fmap. Its type is: Int -> Int |
| | λ addOne n = n + 1 |
| | |
| | -- show has type Int -> String, addOneAndShow is also Int -> String |
| | λ addOneAndShow = show <$> addOne |
| | |
| | -- reverse here has type String -> String, as does addOneShowAndReverse |
| | λ addOneShowAndReverse = reverse <$> addOneAndShow |
| | |
| | -- it works just like function composition would have |
| | λ addOneShowAndReverse 50 |
| | "15" |
| | |
| | -- And for good measure, let's redefine both right next to one another |
| | λ withComposition = reverse . show . (+1) |
| | λ withFmap = reverse <$> show <$> (+1) |
| | |
| | -- See, they work just the same! |
| | λ withComposition 1024 |
| | "5201" |
| | λ withFmap 1024 |
| | "5201" |
To see how this works, we’d like to implement it ourselves. Reimplementing (->) would be a bit tricky, so let’s use a newtype to recreate the same behavior for our own definition of function.
We’ll start by creating a type called Function :
| | newtype Function a b = Function |
| | { runFunction :: a -> b } |
Just like with Either , Function is a type with two type parameters. In this case, the first parameter is the input type to the function, and the second parameter is the output type. Just like with Either , we’ll need to apply a type variable Function first so that we can create a Functor instance:
| | instance Functor ( Function a) where |
When we applied a type variable Either it meant that fmap couldn’t access Left values, but functions don’t have left and right values, so what’s the implication for functions?
Calling fmap might change the type of the second type parameter, but it won’t ever touch the first type parameter. For Function that means fmap might change the return type of the function, but won’t ever change the type of its argument.
Let’s look at an example of the type of fmap when we’re talking about Function values:
| | fmap :: (b -> c) -> Function a b -> Function a c |
This might still make it a little hard to see what’s going on. Let’s look at the type of fmap for a regular (->) function:
| | fmap :: (b -> c) -> (a -> b) -> (a -> c) |
If that looks familiar, it’s because if we strip some unnecessary parentheses then we can see it’s exactly the same type as the function composition operator, (.) :
| | (.) :: (b -> c) -> (a -> b) -> a -> c |
So, writing a Functor instance for Function is nothing more than function composition:
| | instance Functor ( Function a) where |
| | fmap f ( Function g) = Function (f . g) |