🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell List Monad

The List monad is the Monad instance for lists. It chains steps that can each produce many results.

List bind runs the step for every element

Each element gives itself and its tenfold value. The results join in element order.

main :: IO ()
main = print ([1, 2] >>= (\x -> [x, x * 10]))

List bind builds every pairing

Each first choice pairs with 10 and then with 20. The sums appear in pairing order.

main :: IO ()
main = print ([1, 2] >>= (\x -> [10, 20] >>= (\y -> return (x + y))))

An empty step removes that branch

Only values greater than 2 give a result. The smaller values vanish from the final list.

main :: IO ()
main = print ([1, 2, 3, 4] >>= (\x -> if x > 2 then [x] else []))

Example

main :: IO ()
main = print ([1, 2] >>= (\x -> [3, 4] >>= (\y -> [x * 10 + y])))

Key points

  • List monad: the chain for steps where each step gives a list of results.
  • Bind for lists: the operator that runs the next step once for every element and joins the results.
  • Use the List monad to build every combination of choices from earlier steps.
  • Empty list: a step that gives no results and removes that branch from the final list.
  • Return for lists: the function that wraps one value in a one-element list.

In this example, the first choice is 1 or 2 and the second choice is 3 or 4. Each pair forms a two-digit number and the program prints all four numbers in pairing order.

Note

List bind keeps the order of the outer elements first and the inner results second.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is [1, 2] >>= (\x -> [x, x * 10])?