Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 57 ยท Functors, applicatives and monads

Applicative Functors

Learn Haskell's Applicative class: pure, <*>, liftA2 and applicative style for combining independent wrapped values, such as validating form fields.

fmap applies a one-argument function to a value inside a container. What if the function takes two arguments and you have two wrapped values? Try fmap (+) (Just 3) and you get Just (3 +): a function trapped inside a Just. You cannot feed Just 4 to it with fmap, because fmap expects a plain function.

The Applicative class solves exactly that. It lets you apply a wrapped function to a wrapped value, which means you can combine any number of independent computations. It sits between Functor (the previous lesson) and Monad (the next one).

Real Haskell is not installed here, so Haskell blocks are read-only; the runnable examples are JavaScript stand-ins and say so.

pure and <*>

HASKELL
class Functor f => Applicative f where
  pure  :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b
  • pure puts a plain value into the "default" container: pure 5 is Just 5 for Maybe, [5] for lists.
  • <*> (pronounced "ap" or "apply") takes a container holding a function and a container holding an argument, and gives a container with the result.

With <$> and <*> you can lift a function of any arity:

HASKELL
(+) <$> Just 3 <*> Just 4        -- Just 7
(+) <$> Just 3 <*> Nothing       -- Nothing

Read it left to right. (+) <$> Just 3 is Just (3 +). Then <*> Just 4 applies that wrapped function to the wrapped 4. If any piece is Nothing, the whole result is Nothing. This is called applicative style, and it reads almost like normal function application with <$> and <*> sprinkled between the arguments.

Function application, lifted

f x y Plain application.
f <$> mx <*> my The same, inside a functor.

The container decides what happens to missing or multiple values.

1 / 2

The same code, different meaning

For lists, <*> applies every function to every argument:

HASKELL
(+) <$> [1, 2] <*> [10, 20]      -- [11,21,12,22]
(,) <$> "ab" <*> [True, False]
-- [('a',True),('a',False),('b',True),('b',False)]

The instance for Maybe is only a few lines:

HASKELL
instance Applicative Maybe where
  pure = Just
  Just f <*> Just x = Just (f x)
  _      <*> _      = Nothing

For Either e, the first Left stops the computation and becomes the result:

HASKELL
(+) <$> Right 1 <*> Left "bad second"   -- Left "bad second"

liftA2 and friends

liftA2 from Control.Applicative (also exported by the Prelude in recent GHC versions) says the same thing without operators:

HASKELL
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
liftA2 (+) (Just 3) (Just 4)     -- Just 7

Two handy operators drop one side's result: *> runs both and keeps the right value, <* keeps the left. They matter most for IO and for parsers, where the effects of both sides count.

Applicative style in a stand-in

Haskell curries every function, so f <$> a <*> b just works. JavaScript needs curried functions explicitly. This is a stand-in: the Maybe type and the ap function are our own.

JS Maybe and list applicatives

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Validation with Either

Applicative style shines when checking several independent inputs. Each check returns an Either String value, and a record is built only if all succeed:

HASKELL
data User = User { name :: String, age :: Int } deriving Show

checkName :: String -> Either String String
checkName n
  | null n    = Left "name is empty"
  | otherwise = Right n

checkAge :: Int -> Either String Int
checkAge a
  | a < 0     = Left "age is negative"
  | otherwise = Right a

mkUser :: String -> Int -> Either String User
mkUser n a = User <$> checkName n <*> checkAge a

-- mkUser "Ada" 36  == Right (User {name = "Ada", age = 36})
-- mkUser ""    (-1) == Left "name is empty"

Note two things. First, the data constructor User is itself a curried function String -> Int -> User, so it fits <$> directly. Second, the checks do not depend on each other's results: checkAge does not need the name. That independence is what separates applicatives from monads.

With Either, only the first error is reported (the second check is never needed once the first fails). If you want all errors collected, you need a validation-style applicative that combines errors with a monoid, such as Validation from the validation package. See Semigroups and Monoids for the combining idea.

JS Validating fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Applicative laws

You do not need to memorise them, but they explain why the style is safe to refactor:

  • Identity: pure id <*> v == v
  • Homomorphism: pure f <*> pure x == pure (f x)
  • Interchange: u <*> pure y == pure ($ y) <*> u
  • Composition: pure (.) <*> u <*> v <*> w == u <*> (v <*> w)

Informally: pure adds no effect of its own, and <*> is associative. A useful consequence is that pure f <*> x equals fmap f x, which is why every applicative is a functor.

When you see fmap and <*> chains with a constructor at the front, such as Config <$> a <*> b <*> c, think "build a value from independent parts". If a later step needs an earlier result to decide what to do next, you need a monad instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (+) <$> Just 3 <*> Just 4 evaluate to?

    (+) <$> Just 3 is Just (3 +); <*> then applies it to the wrapped 4, giving Just 7.
  2. 2. What does pure 5 produce for the list applicative?

    pure wraps a value in the minimal container for the type; for lists that is a one-element list.
  3. 3. In mkUser "" (-1) using Either String, how many errors are reported?

    Either stops at the first Left. Collecting all errors needs a different applicative, such as Validation.
  4. 4. How many results does (+) <$> [1, 2, 3] <*> [10, 20] have?

    The list applicative combines every element of the first list with every element of the second: 3 times 2.

Summary

  • Applicative adds pure and <*> on top of Functor.
  • f <$> a <*> b <*> c applies an ordinary function to several wrapped values; liftA2 does it for two.
  • The container decides the meaning: Maybe gives up on Nothing, lists try every combination, Either stops at the first Left.
  • Applicative validation builds records from independent checks; collecting every error needs a special type.
  • Use an applicative when the pieces are independent; use a monad when later steps depend on earlier results.

Next: Monads.