Map an Applicative-returning function over a Traversable, collecting effects.
traverse is the central method of the Traversable typeclass. Its type signature is (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b). It applies an effectful function to every element of a structure, sequencing the effects and rebuilding the structure with the results.
traverse generalizes mapM beyond monads to any Applicative. For lists, traverse f xs sequences the f-effects across all elements. For example, traverse readMaybe ["1","2","3"] :: Maybe [Int] returns Just [1,2,3], but Just ["1","oops","3"] returns Nothing. For IO, it runs each action in order and collects results.
traverse is one of the most useful generic functions in modern Haskell. The variant traverse_ from Data.Foldable discards the rebuilt structure, similar to mapM_. The flipped form is for from Data.Traversable. For sequencing existing effects without a transformation, use sequenceA.
| Name | Description | Optional |
|---|---|---|
f |
An Applicative-returning function (a -> f b). | No |
xs |
A Traversable structure of elements (t a). | No |
import Text.Read (readMaybe)
traverse readMaybe ["1", "2", "3"] :: Maybe [Int]
-- Just [1, 2, 3]
traverse readMaybe ["1", "x", "3"] :: Maybe [Int]
-- Nothing
traverse print [1, 2, 3]
-- prints 1, 2, 3; returns IO [(),(),()]