🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Sequence and Traverse

Sequence and traverse are functions that turn a list of wrapped values into one wrapped list. Sequence collects the values and traverse maps a wrapped step first and then collects them.

Sequence collects successful values

Both values are Just values. Sequence collects them into one wrapped list.

main :: IO ()
main = print (sequence [Just 1, Just 2])

One Nothing makes sequence give Nothing

The second value is Nothing. The whole collected result is therefore Nothing.

main :: IO ()
main = print (sequence [Just 1, Nothing])

Traverse doubles each positive value

Traverse doubles 1, 2 and 3 inside Maybe. The collected result keeps their order.

main :: IO ()
main = print (traverse (\x -> if x > 0 then Just (x * 2) else Nothing) [1, 2, 3])

Example

doubleIfPositive :: Int -> Maybe Int
doubleIfPositive x = if x > 0 then Just (x * 2) else Nothing
main :: IO ()
main = do
  print (traverse doubleIfPositive [1, 2, 3])
  print (traverse doubleIfPositive [1, -2, 3])

Key points

  • Sequence: the function that turns a list of wrapped values into a wrapped list.
  • Use sequence when a list of Maybe results must all succeed before the program continues.
  • Traverse: the function that maps a wrapped function over a list and then sequences the results.
  • Failure: one Nothing in the list makes sequence and traverse give Nothing.
  • MapM: the older name for traverse on Monads.

In this example, traverse doubles every value in the first list and prints Just [2,4,6]. The second list has a negative value, so its traverse gives Nothing.

Note

For lists traverse keeps the original order of the elements.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is sequence [Just 1, Nothing]?