The name **applicative functor** is pleasantly descriptive given its functional origins. Functional programmers are notorious for coming up with names like `mappend`

or `liftA4`

, which seem perfectly natural when viewed in the math lab, but hold the clarity of an indecisive Darth Vader at the drive thru in any other context.

Anyhow, the name should spill the beans on what this interface gives us: *the ability to apply functors to each other*.

Now, why would a normal, rational person such as yourself want such a thing? What does it even *mean* to apply one functor to another?

To answer these questions, we'll start with a situation you may have already encountered in your functional travels. Let's say, hypothetically, that we have two functors (of the same type) and we'd like to call a function with both of their values as arguments. Something simple like adding the values of two `Container`

s.

# We can't do this because the numbers are bottled up.add(Container(2), Container(3))# TypeError: unsupported operand type(s) for +: 'Container' and 'Container'# Let's use our trusty mapmaybe_of_add2 = map(add, Container(2))# Container(add(2))

We have ourselves a `Container`

with a partially applied function inside. More specifically, we have a `Container(add(2))`

and we'd like to apply its `add(2)`

to the `3`

in `Container(3)`

to complete the call. In other words, we'd like to apply one functor to another.

Now, it just so happens that we already have the tools to accomplish this task. We can `chain`

and then `map`

the partially applied `add(2)`

like so:

Container(2).chain(lambda two: Container(3).map(add(two)))# Container(5)

The issue here is that we are stuck in the sequential world of monads wherein nothing may be evaluated until the previous monad has finished its business. We have ourselves two strong, independent values and I should think it unnecessary to delay the creation of `Container(3)`

merely to satisfy the monad's sequential demands.

In fact, it would be lovely if we could succinctly apply one functor's contents to another's value without these needless functions and variables should we find ourselves in this pickle jar.

`ap`

is a function that can apply the function contents of one functor to the value contents of another. Say that five times fast.

Container(add(2)).ap(Container(3))# Container(5)# all together nowContainer(2).map(add).ap(Container(3))# Container(5)

There we are, nice and neat. Good news for `Container(3)`

as it's been set free from the jail of the nested monadic function. It's worth mentioning again that `add`

, in this case, gets partially applied during the first `map`

so this only works when `add`

is curried.

We can define `ap`

like so:

class Container:def ap(self, other):return other.map(self.value)

Remember, `self.value`

will be a function and we'll be accepting another functor so we need only `map`

it. And with that we have our interface definition:

An

applicative functoris a pointed functor with an`ap`

method

Note the dependence on **pointed**. The pointed interface is crucial here as we'll see throughout the following examples.

Now, I sense your skepticism (or perhaps confusion and horror), but keep an open mind; this `ap`

character will prove useful. Before we get into it, let's explore a nice property.

F(x).map(f) == F(f).ap(F(x))

In proper English, mapping `f`

is equivalent to `ap`

ing a functor of `f`

. Or in properer English, we can place `x`

into our container and `map(f)`

OR we can lift both `f`

and `x`

into our container and `ap`

them. This allows us to write in a left-to-right fashion:

Maybe(add).ap(Maybe(2)).ap(Maybe(3))# Maybe(5)Task(add).ap(Task(2)).ap(Task(3))# Task(5)

One might even recognise the vague shape of a normal function call if viewed mid squint. We'll look at the pointfree version later in the chapter, but for now, this is the preferred way to write such code. Each value gets transported to the magical land of containers, this parallel universe where each application can be async or null or what have you and `ap`

will apply functions within this fantastical place. It's like building a ship in a bottle.

Did you see there? We used `Task`

in our example. This is a prime situation where applicative functors pull their weight. Let's look at a more in-depth example.

Say we're building a travel site and we'd like to retrieve both a list of tourist destinations and local events. Each of these are separate, stand-alone api calls.

# Http.get :: String -> Task Error HTML@currydef show_table(destinations, events):# show resultspassTask(show_table).ap(Http.get('/destinations')).ap(Http.get('/events'))# Task("a table with dest and events")

Both `Http`

calls will happen instantly and `show_table`

will be called when both are resolved. Contrast this with the monadic version where one `Task`

must finish before the next fires off. Since we don't need the destinations to retrieve events, we are free from sequential evaluation.

Again, because we're using partial application to achieve this result, we must ensure `show_table`

is curried or it will not wait for both `Tasks`

to finish. Incidentally, if you've ever had to do such a thing manually, you'll appreciate the astonishing simplicity of this interface. This is the kind of beautiful code that takes us one step closer to the singularity.

Let's examine a pointfree way to write these applicative calls. Since we know `map`

is equal to `of/ap`

, we can write generic functions that will `ap`

as many times as we specify:

liftA2 = curry(lambda g, f1, f2: f1.map(g).ap(f2))liftA3 = curry(lambda g, f1, f2, f3: f1.map(g).ap(f2).ap(f3))# liftA4, etc

`liftA2`

is a strange name. It sounds like one of the finicky freight elevators in a rundown factory or a vanity plate for a cheap limo company. Once enlightened, however, it's self explanatory: lift these pieces into the applicative functor world.

When I first saw this 2-3-4 nonsense it struck me as ugly and unnecessary. After all, we can check the arity of functions and build this up dynamically. However, it is often useful to partially apply `liftA(N)`

itself, so it cannot vary in argument length.

Let's see this in use:

check_email :: User -> Either str Emailcheck_name :: User -> Either str struser = {'name': 'John Doe','email': 'blurp_blurp',};# create_user :: Email -> str -> IO Usercreate_user = curry(lambda email, name: "...")Either(create_user).ap(check_email(user)).ap(check_name(user))# Left('invalid email')liftA2(create_user, check_email(user), check_name(user))# Left('invalid email')

Since `create_user`

takes two arguments, we use the corresponding `liftA2`

. The two statements are equivalent, but the `liftA2`

version has no mention of `Either`

. This makes it more generic and flexible since we are no longer married to a specific type.

Let's see the previous examples written this way:

liftA2(add, Maybe(2), Maybe(3))# Maybe(5)liftA2(show_table, Http.get('/destinations'), Http.get('/events'));# Task("a table with dest and events")

In languages like Haskell, Scala, PureScript, and Swift, where it is possible to create your own infix operators you may see syntax like this:

-- Haskell / PureScriptadd <$> Right 2 <*> Right 3

# pythonmap(add, Right(2)).ap(Right(3))

It's helpful to know that `<$>`

is `map`

and `<*>`

is just `ap`

. This allows for a more natural function application style and can help remove some parenthesis.

We haven't spoken much about derived functions. Seeing as all of these interfaces are built off of each other and obey a set of laws, we can define some weaker interfaces in terms of the stronger ones.

For instance, we know that an applicative is first a functor, so if we have an applicative instance, surely we can define a functor for our type.

This kind of perfect computational harmony is possible because we're working within a mathematical framework. Mozart couldn't have done better even if he had torrented Ableton as a child.

I mentioned earlier that `ap`

is equivalent to `map`

. We can use this knowledge to define `map`

for free:

# map derived from of/apdef map(self, f)return Container(f).ap(self)

Monads are at the top of the food chain, so to speak, so if we have `chain`

, we get functor and applicative for free:

# map derived from chaindef map(self, f):return self.chain(lambda a: Container(f(a)))# ap derived from chain/mapdef ap(self, other):return self.chain(lambda f: other.map(f))

If we can define a monad, we can define both the applicative and functor interfaces. This is quite remarkable as we get all of these can openers for free. We can even examine a type and automate this process.

It should be pointed out that part of `ap`

's appeal is the ability to run things concurrently so defining it via `chain`

is missing out on that optimization. Despite that, it's good to have an immediate working interface while one works out the best possible implementation.

Why not just use monads and be done with it, you ask? It's good practice to work with the level of power you need, no more, no less. This keeps cognitive load to a minimum by ruling out possible functionality. For this reason, it's good to favor applicatives over monads.

Monads have the unique ability to sequence computation, assign variables, and halt further execution all thanks to the downward nesting structure. When one sees applicatives in use, they needn't concern themselves with any of that business.

Now, on to the legalities ...

Like the other mathematical constructs we've explored, applicative functors hold some useful properties for us to rely on in our daily code. First off, you should know that applicatives are "closed under composition", meaning `ap`

will never change container types on us (yet another reason to favor over monads). That's not to say we cannot have multiple different effects - we can stack our types knowing that they will remain the same during the entirety of our application.

To demonstrate:

t_of_m = compose(Task, Maybe)liftA2(liftA2(concat), t_of_m('Rainy Days and Mondays'), t_of_m(' always get me down'))Task(Maybe(Rainy Days and Mondays always get me down))

See, no need to worry about different types getting in the mix.

Time to look at our favorite categorical law: *identity*:

# identityA(id).ap(v) == v

Right, so applying `id`

all from within a functor shouldn't alter the value in `v`

. For example:

v = Identity('Pillow Pets')Identity(id).ap(v) == v

`Identity(id)`

makes me chuckle at its futility. Anyway, what's interesting is that, as we've already established, `ap`

is the same as `map`

so this law follows directly from functor identity: `map(id) == id`

.

The beauty in using these laws is that, like a militant kindergarten gym coach, they force all of our interfaces to play well together.

# homomorphismA(f).ap(A(x)) == A(f(x))

A *homomorphism* is just a structure preserving map. In fact, a functor is just a *homomorphism* between categories as it preserves the original category's structure under the mapping.

We're really just stuffing our normal functions and values into a container and running the computation in there so it should come as no surprise that we will end up with the same result if we apply the whole thing inside the container (left side of the equation) or apply it outside, then place it in there (right side).

A quick example:

Either(to_upper_case).ap(Either('oreos')) == Either(to_upper_case('oreos'))

The *interchange* law states that it doesn't matter if we choose to lift our function into the left or right side of `ap`

.

# interchangev.ap(A(x)) == A(lambda f: f(x)).ap(v)

Here is an example:

v = Task(reverse)x = 'Sparklehorse'v.ap(Task(x)) == Task(lambda f: f(x)).ap(v)

And finally composition which is just a way to check that our standard function composition holds when applying inside of containers.

# compositionA(compose).ap(u).ap(v).ap(w) == u.ap(v.ap(w))

u = IO(to_upper_case)v = IO(concat('& beyond'))w = IO('blood bath ')IO(compose).ap(u).ap(v).ap(w) == u.ap(v.ap(w))

A good use case for applicatives is when one has multiple functor arguments. They give us the ability to apply functions to arguments all within the functor world. Though we could already do so with monads, we should prefer applicative functors when we aren't in need of monadic specific functionality.

We're almost finished with container apis. We've learned how to `map`

, `chain`

, and now `ap`

functions. In the next chapter, we'll learn how to work better with multiple functors and disassemble them in a principled way.