Haskell traverse and sequenceA for Everyday Code
You wrote a function that parses one line of a config file and hands back a Maybe Int. Then you mapped it over the twelve lines of the file and got [Maybe Int], which is not a type any caller wants to deal with.

You wrote a function that parses one line of a config file and hands back a Maybe Int. Then you mapped it over the twelve lines of the file and got [Maybe Int], which is not a type any caller wants to deal with. What you actually need is Maybe [Int]: either every line parsed and you have your list, or something is wrong and the whole file is rejected. Swapping the order of those two type constructors is the entire job of traverse and sequenceA.
This walkthrough starts from that shape of problem, builds the fix in ghci one line at a time, and then shows the two places where reaching for traverse costs you memory instead of saving you work. Everything here lives in Data.Traversable, which comes with base, so there is nothing to install. I am assuming you can read a type signature with a class constraint in it and that Maybe and Either are already familiar.
Where the nested type comes from
Put this in a file and load it. The parser is deliberately dumb so the types stay readable.
parsePort :: String -> Maybe Int reads a line like "8080" with readMaybe and returns Nothing on anything else. Now in ghci try map parsePort ["8080", "9090", "oops"]. You get [Just 8080, Just 9090, Nothing]. The failure is in there somewhere, but to find it you have to walk the list yourself, and to build the success case you have to walk it again with fromJust, which is how a crash ends up in production three months later.
The shape you want is one layer out. Try traverse parsePort ["8080", "9090", "oops"] and you get Nothing. Drop the bad entry and you get Just [8080, 9090]. The effect was pulled out of the list and collapsed into a single answer.
In my second week of teaching this, the question I get is always the same: did it stop early? Yes for Maybe and Either. The moment one element produces Nothing, the rest of the list is never looked at, because the Applicative instance for Maybe short circuits. That matters if your per element work is expensive, and it bites if you were relying on a side effect happening for every element.
The one signature worth memorising
Here is the type, trimmed to the list case so there is less noise:
traverse :: Applicative f => (a -> f b) -> [a] -> f [b]
Read it right to left. You have a list of a. You have a function that turns one a into an effectful b. You get back one effect that produces the whole list. Nothing more is happening. The class constraint is Applicative, not Monad, which is why traverse works for things like Validation types that are not monads at all.
sequenceA is the same machine with the function already applied. sequenceA :: Applicative f => [f a] -> f [a]. You reach for it when the effects are already sitting in the list, usually because some other function built them. People love to point out that sequenceA equals traverse id. That is true and it teaches you nothing, so ignore it until after you have used both a few times.
These four names come up constantly and get mixed up constantly, so here they are side by side:
| Name | Argument order | Keeps results? | Reach for it when |
|---|---|---|---|
| traverse | function, then container | yes | default choice |
| for | container, then function | yes | the lambda is long |
| sequenceA | container of effects | yes | effects already built |
| traverse_ | function, then container | no | you only want the effect |
mapM and sequence are the older Monad only versions. They still work and plenty of code uses them, but there is no reason to write new code with them.
Keeping the error instead of throwing it away
Maybe tells you something failed. It never tells you what, and a config loader that says Nothing to a user is a bug report waiting to happen. Change the parser to return Either String Int and the call site does not change at all.
Write parsePortE :: String -> Either String Int so it returns Left ("not a port: " ++ s) on failure. Then traverse parsePortE ["8080", "oops", "nope"] gives you Left "not a port: oops". Same function, same arguments, better message, and the type of the result is now Either String [Int].
Notice which error you got. Either stops at the first Left, so "nope" is never reported. If you want all three failures at once, which is what a form validator needs, Either is the wrong Applicative and no amount of traverse will fix it. You want a validation type whose Applicative instance accumulates with a Semigroup, such as Validation from the validation package or the Data.Validation module people copy into their own projects. The pattern of choosing your error type before you write the parser is covered in more depth in our guide to error handling with Either.
One more thing worth trying in ghci, because it surprises people: traverse over a tuple only touches the second element. traverse Just (1, 2) is Just (1, 2), and the 1 was never visited. Traversable instances for tuples, Map and Either all work on the last type parameter only. For a Map, that means keys are left alone and values get traversed, which is almost always what you wanted anyway.
The IO case
IO is an Applicative, so all of this applies to reading files. traverse readFile ["a.conf", "b.conf"] gives you IO [String]. This is where the first real trap lives, and it is the subject of the next section.
The advice I disagree with
The common guidance is that traverse is the general tool so you should default to it everywhere and stop thinking about mapM. The first half is fine. The second half quietly teaches people to build lists they do not need.
Say you have 200,000 log lines and you want to write each one to a socket. Writing traverse sendLine logLines works, and it also allocates a 200,000 element list of unit values that you immediately discard. In a test on GHC 9.6 with a trivial send action, that version allocated roughly 19 MB more than the same loop written with traverse_, and the gap grows with the list. The underscore versions throw the results away on purpose. Use them whenever the return value is ().
The second trap is strictness. traverse for the State monad and for lazy structures builds thunks, same as any other fold, and a traverse over a big list inside a lazy State computation is a classic way to blow the heap. If you are chasing one of those, the technique is the same as for any other leak and we walk through it in finding and fixing a Haskell space leak.
The third thing nobody mentions: traverse on a list is not a loop you can exit with a value. If you want to stop at the third match and return it, traverse is the wrong shape and you want a fold or a find. I have watched students spend twenty minutes trying to make traverse do an early return with a result attached, and the answer is that it cannot, except as a failure.
Three exercises that make it stick
Do these in ghci, in order. They take about fifteen minutes total and they cover the cases you will actually meet.
- Write lookupAll :: [String] -> Map String Int -> Maybe [Int] using traverse and a flipped Map.lookup. If any key is missing, the whole thing is Nothing. The Map side of this is covered in our Data.Map tutorial.
- Change the return type to Either String [Int] so a missing key names itself, then confirm in ghci that only the first missing key appears.
- Write the same thing with traverse_ and a print action, and compare what the two type signatures tell a reader about what the function does.
If the third one feels pointless, that is the point. The underscore in the name is documentation: it says this function is here for the effect and the results are gone. That signal is worth more than the few bytes it saves.
FAQ
Is traverse the same as mapM?
For any Monad, yes, the results are identical. traverse has the weaker Applicative constraint, so it works in more places. New code should use traverse.
Why does traverse stop at the first failure?
Because that is what the Applicative instance for Maybe and Either does. It is not a property of traverse. Give it an Applicative that accumulates, like a Validation type, and you collect every failure instead.
Can I traverse something other than a list?
Anything with a Traversable instance, which includes Maybe, Either, Map, Seq, Vector and most tree types in libraries. Writing an instance for your own tree type takes about four lines once you have derived Functor and Foldable.
What should I read next?
Traversable sits directly on top of Applicative, so if the pure and star operators still feel shaky, go back to the tutorials index and work through Functor and Applicative before pushing further.
More in Tutorials
Tutorials
Haskell Reader Monad Tutorial for App Configuration
You start a service with one configuration field, a database connection string.
Tutorials
Haskell Data.Vector Tutorial for Fast Numeric Arrays
Your program reads 8 million sensor readings, sums them, and takes nineteen seconds while resident memory climbs past 900 MB.
Tutorials
Haskell State Monad Tutorial With a Working Example
You have a function that needs a counter, a random seed or a running total, and passing that value in and out of every call has...