🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Applicative Class

Applicative is a typeclass for applying a wrapped function to a wrapped value. It builds on Functor by adding a way to wrap a plain value and a way to apply wrapped functions.

Pure wraps a plain value

Pure puts a plain value inside a wrapper. The wrapper type decides the shape of the result.

main :: IO ()
main = do
  print (pure 5 :: Maybe Int)
  print (pure 5 :: [Int])

Apply runs a wrapped function

The operator <*> takes a wrapped function on the left and a wrapped value on the right. Both sides must be present for a Maybe result to appear.

main :: IO ()
main = do
  print ((+) <$> Just 2 <*> Just 3)
  print ((\x y -> x - y) <$> Just 10 <*> Just 3)

Pure and apply can do mapping

Mapping is applying a wrapped function built from pure. The two lines below give the same result.

main :: IO ()
main = do
  print ((+1) <$> Just 3)
  print (pure (+1) <*> Just 3)

Example

main :: IO ()
main = do
  print (pure (+) <*> Just 20 <*> Just 5)
  print (pure (+) <*> Just 20 <*> Nothing)

Key points

  • Applicative: a typeclass for applying a wrapped function to a wrapped value.
  • Pure: pure wraps a plain value inside an Applicative type.
  • Apply: the operator <*> applies a wrapped function to a wrapped value.
  • Wrapped function: a function stored inside a type such as Maybe or a list.
  • Wrapped value: a plain value stored inside the same kind of type.
  • Functor link: every Applicative is also a Functor because mapping is a special case of applying.

In this example, the first line adds two wrapped numbers and the second line shows that a missing number gives Nothing instead of a sum.

Note

the same Applicative operations work for Maybe and for lists but the pairing rule differs by type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is pure (+) <*> Just 2 <*> Just 3?