Now that you’ve seen several different examples of types that can have a lawful Functor instance, let’s move on and take a look at Applicative :
| | class Functor f => Applicative f where |
| | pure :: a -> f a |
| | |
| | infixl 4 <*> |
| | (<*>) :: f (a -> b) -> f a -> f b |
One thing that is new here is the use of \=> to define a constraint as part of our type class definition. This works just like it does when you use type constraints in functions. In this case, it allows us to express that anything that can be an instance of Applicative must also provide an instance for Functor . We won’t see any examples of this until later chapters, but you can also introduce constraints when you define instances.
The Applicative type class that we’ve defined has two functions that we really care about: pure , and the unfortunately hard to pronounce (<*>) . The real Applicative type class also has three extra functions: liftA2 , (*>) and (<*) . We’ll ignore those last three for now, because they can all be implemented in terms of pure and (<*>) .
So, what is an Applicative ? In the structural view of the world, we said that Functor represents a class of things that allow us apply a function that would change the type or value of the Functor without changing its underlying structure. In this structural view of things, an Applicative allows you to use pure to introduce a plain value while giving it some new structure, and it allows you to use (<*>) to take two values that each have their own structure and to combine those structures in some way.
Alternatively, in the computational view of the world we said that a Functor was something that would allow us to provide a function to modify the result that we would eventually end up computing. In this computational view of the world, pure allows us to introduce some pure value into a new computation. IO is a great example of this. If we create an IO action using pure , we get back a pure IO action that will result in the value we originally passed in without having any other side effects. In the computational view of (<*>) , we can create a new computation that will generate its result by evaluating two other computations and combining their results. For example, if we view Maybe as a computation that might or might not complete, then when we say f <*> a , we are creating a new computation that will return a value if, and only if, it can run the computation f and get a function, and run the computation a to get a value to apply to that function. If either of those computations fail, then the entire computation fails.
Let’s look at a couple of complete examples of creating Applicative instances so that we can get a better feel for how they work. We’ll start again with Maybe . The Applicative instance for Maybe is short and simple:
| | instance Applicative Maybe where |
| | pure = Just |
| | Nothing <*> _ = Nothing |
| | Just f <*> a = f <$> a |
As you learned earlier, pure is typically defined by a constructor. In the case of Maybe , we can use Just , which already does exactly what we need. Our definition of <*> is also pretty straightforward. The applicative instance of Maybe lets us apply an optional function, so if the function we want to apply is Nothing , then we return Nothing . If we have a real function value, then we apply it using fmap .
Like we did with functors, let’s run through a few examples of using the applicative instance for Maybe so that we can get a feel for how it works:
| | -- Pure returns Just value |
| | λ pure 1 :: Maybe Int |
| | Just 1 |
| | -- <*> Applies Just func to Just val giving Just (func val) |
| | λ Just (+1) <*> pure 1 |
| | Just 2 |
| | -- Just func <*> Nothing returns Nothing |
| | λ Just (unwords . reverse . words) <*> Nothing |
| | Nothing |
| | -- Create a function that returns an optional function |
| | λ let addSome x = if x < 5 then Just (+x) else Nothing |
| | -- If we get a function then we can apply it |
| | λ addSome 3 <*> Just 1 |
| | Just 4 |
| | -- If we get Nothing then we return Nothing |
| | λ addSome 5 <*> Just 1 |
| | Nothing |
Just like with functor, Either a also has an Applicative instance, and it is quite similar to the instance we’ve just defined for Maybe :
| | instance Applicative ( Either a) where |
| | pure a = Right a |
| | ( Left err) <*> _ = Left err |
| | ( Right f) <*> g = f <$> g |
Not all of the Applicative instances we can define are quite as straightforward as their Functor counterparts though. Lists, for example, have a bit more structure to them than Either or Maybe , and so we have to do a little bit more work to write a reasonable Applicative instance.
Let’s continue with our own List type and look into what an Applicative list instance looks like. We’ll start with pure :
| | instance Applicative List where |
| | pure a = List a Empty |
The definition of pure does turn out to be fairly straightforward: we have a value and we create the minimal required structure to hold that value, which is a single-element list.
What about (<*>) ? To write an implementation of <*> , we need to think about what it means to merge the structure of two lists. With Maybe we returned Nothing if we had no function. The equivalent for lists would be to return an empty list if we have an empty list of functions, so let’s start there:
| | Empty <*> _ = Empty |
So far, so good, but if we have a non-empty list on the left, then that’s a structure that we somehow have to combine with the list, empty or not, on the right. How can we do this?
Each element of our left-hand list is a function. One place to start with would be to fmap each of those functions over the right-hand list. We could try by writing this:
| | a <*> b = fmap (`fmap` b) a |
Unfortunately this won’t work. The type of the function we’ve just defined is:
| | List (a -> b) -> List a -> List ( List b) |
But our fmap implementation is required to have the type:
| | fmap :: (a -> b) -> List a -> List b |
The only reasonable thing we can do is to concatenate each of the lists that we are generating by fmap ing the elements of our first list onto our second list. That means we’ll need to write a function to concatenate lists:
| | -- Equivalent to (<>) on regular lists |
| | concatList :: List a -> List a -> List a |
| | concatList Empty as = as |
| | concatList ( List a as) bs = List a (concatList as bs) |
Now that we have a way of combining lists, we can use it to write the rest of our applicative instance. For each function in our left-hand list, we’ll want to fmap the function over the right-hand list, and then concatenate that list to the result of calling <*> on the rest of the left-hand operand:
| | List f fs <*> vals = |
| | (fmap f vals) `concatList` (fs <*> vals) |
Here’s the final version of our applicative instance with everything put together:
| | instance Applicative List where |
| | pure a = List a Empty |
| | Empty <*> _ = Empty |
| | List f fs <*> vals = (f <$> vals) `concatList` (fs <*> vals) |
Finally, let’s again run through a few examples of how we can use the applicative instance for List so that we can start to develop an intuition for how it works:
| | -- define funcList and numList to use throughout these examples |
| | λ let funcList = toList [id, succ, (*2)] |
| | λ let numList = toList [1..5] |
| | -- the result of <*> is the concatenation of each function fmapped to the list |
| | λ fromList $ funcList <*> numList |
| | [1,2,3,4,5,2,3,4,5,6,2,4,6,8,10] |
| | -- Using an empty list as the left-hand operand returns and empty list |
| | λ fromList $ Empty <*> numList |
| | [] |
| | -- Using an empty list as the right-hand operand returns and empty list |
| | λ fromList $ funcList <*> Empty |
| | [] |
| | -- We can combine pure with <*> to apply a single function to our list |
| | λ fromList $ pure (replicate 2) <*> numList |
| | [[1,1],[2,2],[3,3],[4,4],[5,5]] |
As a final example, let’s also consider Function and what an Applicative instance for it might look like. Just like all of our examples so far, pure is fairly easy: we can lift a pure value into a function by writing a function that always returns that value:
| | instance Applicative ( Function a) where |
| | pure a = Function $ const a |
Our definition of (<*>) will be trickier. Let’s start by looking at the types involved. Remember that the general type of (<*>) is:
| | (<*>) :: f (a -> b) -> f a -> f b |
For Function in particular, that means:
| | (<*>) :: Function a (b -> c) -> Function a b -> Function a c |
The first thing we have to ask ourselves is, what does Function a (b -> c) even mean? If we strip away the newtype wrapper, it means we have a function of the type:
| | a -> (b -> c) |
Of course we can remove the parentheses here and see that what we’re really talking about is just:
| | a -> b -> c |
To make things a little bit more clear, let’s also look at the unwrapped version of (<*>) for plain functions:
| | fmap :: (a -> b -> c) -> (a -> b) -> a -> c |
That’s a little bit of something to try to wrap our heads around! Thankfully, we can get some help if we let the type drive our implementation. Let’s start writing this with some blank spots, and fill them in as we think through what we need to do to satisfy the required type. We’ll start by just writing the left-hand side of the implementation:
| | Function f <*> Function g = |
Here, f will have the type f :: a -> b -> c and g will have the type g :: a -> b . Let’s keep those in mind as we take a step forward. We need to return a value with the type Function a c . That means we need to return a function that takes a value of type a :
| | Function f <*> Function g = Function $ \ value -> |
We need to return a value of type c and the only way to get one is to call f with a value of type a and a value of type b . value has type a so we can start there:
| | Function f <*> Function g = Function $ \ value -> |
| | f value _ |
We also need to pass f a value of type b . The only way to get one of those is to apply value to g . That gives us the final version of our (<*>) implementation for Function :
| | instance Applicative ( Function a) where |
| | pure a = Function $ const a |
| | Function f <*> Function g = Function $ \ value -> f value (g value) |
In reality, the Applicative instance of functions doesn’t come up all that often in this form, but it’s helpful to understand that there is a valid instance so that you don’t get overly fixated on the idea of these type classes as “containers.” The Applicative instance of functions does give rise to one particularly interesting piece of code golf though. We can use it to define an extremely terse implementation of the Fibonacci sequence:
| | λ fibs = 0 : 1 : (zipWith (+) <*> tail) fibs |
| | λ take 10 fibs |
| | [0,1,1,2,3,5,8,13,21,34] |
Now that we’ve looked at functors and applicatives, we can look at monads. In the next section, we’ll talk about monads and how they relate to IO and interacting with the local system.