Applicative

Let’s start with how the Applicative class is defined. From the definition, we can see that Applicatives they are Functors with two more operations, which is pure and apply. pure wraps some value to make an applicative functor. apply is a bit more complicated.

Let’s just look at its type, does that ring a bell? Yeah, it looks like map except we have functions wrapped in side an applicative functor. What apply does is extract the function(s) from the functor and map them to the f a .

  1. class Functor f => Applicative f where
  2. pure :: forall a. a -> f a
  3. apply :: forall a b. f (a -> b) -> f a -> f b
  4. infixl 4 apply as <*>

Here are some examples of intances of Applicatve

  1. instance Applicative Maybe where
  2. pure = Just
  3. Nothing <*> mb = Nothing
  4. (Just f) <*> mb = map f mb

Let’s have a closer look at instance Applicative [] , we can see that every f in the list will get applied to all the elements in the list. So with (+) <$> [1,2] <*> [3,4,5], we will have a non-deterministic computation on (+).