🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Applicative Maybe

Applicative Maybe applies a wrapped function only when both wrapped values are present. A missing value on either side makes the result missing.

Two present values combine normally

Two present values combine normally. The function runs on the values inside the wrappers.

main :: IO ()
main = do
  print ((+) <$> Just 2 <*> Just 3)
  print ((*) <$> Just 4 <*> Just 5)

A missing side gives Nothing

A missing side stops the whole combination. The result is Nothing in both lines.

main :: IO ()
main = do
  print ((+) <$> Just 2 <*> (Nothing :: Maybe Int))
  print ((+) <$> (Nothing :: Maybe Int) <*> Just 3)

Apply chains for three inputs

Apply chains from left to right for more inputs. Each new wrapped value feeds the next input of the function.

main :: IO ()
main = do
  print ((\a b c -> a + b + c) <$> Just 1 <*> Just 2 <*> Just 3)
  print ((\a b c -> a + b + c) <$> Just 1 <*> (Nothing :: Maybe Int) <*> Just 3)

Example

main :: IO ()
main = do
  print ((++) <$> Just "Hello, " <*> Just "Ana")
  print ((++) <$> Just "Hello, " <*> (Nothing :: Maybe String))

Key points

  • Maybe apply: the operator <*> combines a wrapped function and a wrapped value inside Maybe.
  • Present values: two Just values combine into a Just result.
  • Missing function: a Nothing function gives Nothing even when the value is present.
  • Missing value: a Nothing value gives Nothing even when the function is present.
  • Three values: a function with three inputs can take three wrapped values in order.

In this example, the first line joins a greeting and a name inside Maybe and the second line shows that a missing name gives Nothing instead of a greeting.

Note

Maybe apply never invents a missing value and never reports why a value is missing.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is (+) <$> Just 2 <*> Nothing?