Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 57 ยท Functors, applicatives and monads

Monads

A clear, myth-free introduction to Haskell monads: the >>= operator, Maybe and list monads, the three monad laws, and a runnable JavaScript stand-in.

Monads have a reputation for being mysterious. They are not. A monad is a small interface for chaining steps where each step may depend on the result of the previous one, while the container (the monad) quietly handles something extra: a possible failure, several answers, an environment, an effect.

You have met the ingredients already. Functors apply a plain function inside a container. Applicatives combine independent containers. Monads add one more power: the next step can choose what to do based on the value that came out of the last one.

Real Haskell is not installed on this site, so Haskell blocks are read-only. The runnable examples are JavaScript stand-ins that mimic the behaviour and say so.

The problem: chains of fallible steps

Suppose you look up a user's id, then use it to look up an address, then take the postcode. Each lookup returns a Maybe:

HASKELL
userId   :: String -> Maybe Int
address  :: Int -> Maybe String
postcode :: String -> Maybe String

Without help you write nested case expressions:

HASKELL
postcodeOf :: String -> Maybe String
postcodeOf name =
  case userId name of
    Nothing -> Nothing
    Just uid ->
      case address uid of
        Nothing -> Nothing
        Just addr -> postcode addr

Every step repeats the same line: "if Nothing, stop; otherwise continue". The pattern is always identical, so we can name it.

The bind operator

HASKELL
class Applicative m => Monad m where
  (>>=)  :: m a -> (a -> m b) -> m b
  return :: a -> m a          -- same as pure

>>= is pronounced bind. Its left argument is a wrapped value, its right argument is a function that takes a plain value and returns a new wrapped value. Compare the types:

HASKELL
fmap  :: (a -> b)   -> f a -> f b
(>>=) :: m a -> (a -> m b) -> m b

fmap takes a function that returns a plain result. Bind takes a function that returns another monadic value, and it flattens the nesting so you never end up with Maybe (Maybe b).

For Maybe:

HASKELL
instance Monad Maybe where
  Nothing >>= _ = Nothing
  Just x  >>= f = f x

Now the lookup chain collapses:

HASKELL
postcodeOf :: String -> Maybe String
postcodeOf name = userId name >>= address >>= postcode

>>= is left-associative, so this reads left to right like a pipeline. If any step gives Nothing, the rest is skipped.

Bind in three moves

Look inside Is there a value?
Feed the function Give it to the next step.
Flatten One layer of wrapping, not two.
1 / 2

The list monad

For lists, >>= is "apply the function to each element and concatenate the results":

HASKELL
instance Monad [] where
  xs >>= f = concatMap f xs

[1, 2, 3] >>= \x -> [x, x * 10]      -- [1,10,2,20,3,30]

This models nondeterminism: each element is one possible value and the function says what could follow. Chaining two binds explores every combination:

HASKELL
[1, 2] >>= \x -> "ab" >>= \c -> [(x, c)]
-- [(1,'a'),(1,'b'),(2,'a'),(2,'b')]

That is the same idea behind list comprehensions in List Comprehensions.

A runnable stand-in

Here is a Maybe monad with bind as a function. Real Haskell gives you >>= as an operator and picks the instance by type. In JavaScript we write it by hand, but the control flow is identical.

JS Chaining Maybe lookups

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

No output.

JS The list monad: all combinations

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

No output.

Notice the trick in the second example: returning [] means "this branch has no answer", just like Nothing. That is how guards work inside list monad code.

The monad laws

A monad instance must satisfy three laws, written with return and >>=:

  1. Left identity: return a >>= f is the same as f a.
  2. Right identity: m >>= return is the same as m.
  3. Associativity: (m >>= f) >>= g is the same as m >>= (\x -> f x >>= g).

They guarantee that return is a neutral step and that how you group a chain does not matter, only the order. That is what lets you refactor a long chain by pulling a few steps into a helper function without changing behaviour.

JS Checking the laws for Maybe

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

No output.

Myths worth dropping

  • "A monad is a container." Lists and Maybe look like containers, but IO is not one: an IO String does not hold a string, it describes an action that produces one. A function r -> a is also a monad.
  • "Monads are about side effects." Maybe, Either and lists have no side effects. IO is just one instance.
  • "You must understand category theory." You do not. Knowing >>= and the three laws is enough to use monads well.
  • "Monads are a burrito, a box, a spacesuit..." Metaphors help one person and confuse the next. Prefer the type: m a -> (a -> m b) -> m b.

>> is bind that ignores the previous value: a >> b means a >>= \_ -> b. It is how plain sequencing is written. In do-Notation Demystified you will see that do blocks are just sugar for these operators.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of (>>=)?

    Bind takes a wrapped value and a function that returns another wrapped value. The first option is fmap with swapped arguments, the second is <*>.
  2. 2. What does Just 4 >>= \x -> if x > 5 then Just x else Nothing give?

    The function returns Nothing for 4, and bind does not wrap it again, so the result is plain Nothing.
  3. 3. Which statement about monads is true?

    Monads are an interface for chaining dependent steps. Maybe and lists are monads, and neither performs side effects.
  4. 4. What does the right identity law say?

    Binding to return changes nothing; return is a neutral step.

Summary

  • A monad provides >>= (bind) and return for chaining steps where each can depend on the last result.
  • Maybe stops at the first Nothing, Either stops at the first error, and lists explore every possibility.
  • Bind flattens: the function returns a wrapped value, and you do not get nested wrappers.
  • The laws (left identity, right identity, associativity) make chains safe to regroup.
  • A monad is an interface, not a container and not only about side effects.

Next: do-Notation Demystified.