Lesson 42 of 55
10 mins readPython Monadic Utilities: sequence, mapM, forM & when
In Plain English
Control.Monad provides high-level utilities to orchestrate monadic collections: sequence turns [m a] into m [a], mapM maps an effectful function over a list, and when runs conditional actions.
Deep Dive: How It Works
sequence: [Just 1, Just 2, Just 3] -> Just [1, 2, 3]; if any item is Nothing, returns Nothing.
mapM: mapM f xs applies effectful f to all xs and sequences results into a single monadic container.
forM: Like mapM but with flipped argument order (forM xs f), ideal for multi-line do blocks.
when / unless: when cond action executes action only when boolean cond is True.
Core Rules to Remember

sequence [m a] -> m [a]: Transforms a list of actions into a single action returning a list.

forM for Looping: The idiomatic functional equivalent of imperative foreach loops in IO.
Live Interactive Example
Hit Run Code to see it liveUsing mapM and sequence
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: sequence combines a list of Maybes; forM iterates over [1..3] in IO.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Sequence List of Maybes
Compute `sequence [Just 10, Just 20]` and print `"Sequenced: "` followed by its `show` string.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.