🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Bind and Return

Bind and return are the two core operations of the Monad class. Bind chains wrapped steps and return wraps a plain value.

Bind applies the function inside the wrapper

The function multiplies 4 by 10. The result stays wrapped in Maybe.

main :: IO ()
main = print (Just 4 >>= (\x -> Just (x * 10)))

Return wraps a value for each wrapper

The first line wraps 7 in Maybe. The second line wraps 3 in a list.

main :: IO ()
main = do
  print (return 7 :: Maybe Int)
  print (return 3 :: [Int])

Nothing stops a bind chain

The first value is missing. The addition never runs and the result is Nothing.

main :: IO ()
main = print ((Nothing :: Maybe Int) >>= (\x -> Just (x + 1)))

Example

main :: IO ()
main = print (Just 20 >>= (\x -> if x > 10 then Just (x - 5) else Nothing) >>= (\y -> Just (y * 2)))

Key points

  • Bind: the operator written as >>= that feeds a wrapped value into a wrapped step.
  • Use bind when the next step needs the unwrapped result of the previous step.
  • Return: the function that wraps a plain value with no extra effect.
  • Use return as the last step when a chain must end with a wrapped value.
  • Short-circuit: a Nothing step stops the rest of the chain and the whole result is Nothing.

In this example, Just 20 passes the test and becomes Just 15. Then bind doubles 15 inside Maybe and the program prints Just 30.

Note

For lists return wraps one value in a one-element list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does return 9 :: Maybe Int print?