Applicative functor
Because Maybe
is a Functor
, we can lift the (+2)
function so that it can be applied directly to a Maybe
value (Just
or Nothing
):
fmap (+2) (Just 3)
However, fmap
does not enable us to apply a function to multiple Functor
values:
fmap (+) (Just 2) (Just 3)
For that, we need the Applicative Functor
type-class, which enables us to raise a function to act on multiple Functor
values:
–- Applicative inherits from Functor class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b
The pure function lifts a value into the Functor
typeclass while the <*>
operator generalizes function application to Functor (hence the term Applicative Functor
). Let's see how this works by making Maybe
' an instance of Applicative
:
import Control.Applicative
data Maybe' a = Just' a | Nothing'
deriving (Show)
–- we still need the Functor instance
instance Functor Maybe' where
fmap _ Nothing' = Nothing'
fmap f (Just' x) = Just...