Applicative Functors in Haskell

Applicative Functors in Haskell extend on the idea of Functors.

Functors are things that can be mapped over. Another way of looking at functorsis as values with an added context. For instance, Maybe values have the extra context that they may have failed. Whit lists, the context is that the value can actually be several values or none.

Applicative Functors are enhanced Functors.

With ordinary functors we map functions that take only one parameter.If we map a function that takes 2 arguments over a functor we get a function that is wrapped in a context.

For example doing:

1

fmap (*) (Just3)

gives us the result:

1

Just (* 3)

which is a function wrapped in a Just.

By mapping “multiparameter” functions over functor val-ues, we get functor values that contain functions inside them. Whatcan we do with them? We can map functions that take these functionsas parameters over them, because whatever is inside a functor value will begiven to the function that we’re mapping over it as a parameter:

1

2

3

4

5

6

Prelude> let a = fmap (*) [1,2,3,4]

Prelude> :t a

a :: [Integer -> Integer]

Prelude> fmap (\f -> f 9) a

[9,18,27,36]

Prelude>

But what if we have a functor value of Just (3 ) and a functor valueof Just 5, and we want to take out the function from Just (3 ) and mapit over Just 5? We cannot do this with normal functors because they sup-port only mapping normal functions over existing functors. Even when wemapped \f -> f 9 over a functor that contained functions, we were just map-ping a normal function over it. But we can’t map a function that’s inside afunctor value over another functor value with what fmap offers us.We can do this using the Applicative type class. The Applicative is a functor with application. It provides operations to embed pure expressions and sequence computations and combine their results.