Haskell Language Performing a side-effect for each element of a Foldable structure


traverse_ executes an Applicative action for every element in a Foldable structure. It ignores the action's result, keeping only the side-effects. (For a version which doesn't discard results, use Traversable.)

-- using the Writer applicative functor (and the Sum monoid)
ghci> runWriter $ traverse_ (\x -> tell (Sum x)) [1,2,3]
((),Sum {getSum = 6})
-- using the IO applicative functor
ghci> traverse_ putStrLn (Right "traversing")
ghci> traverse_ putStrLn (Left False)
-- nothing printed

for_ is traverse_ with the arguments flipped. It resembles a foreach loop in an imperative language.

ghci> let greetings = ["Hello", "Bonjour", "Hola"]
ghci> :{
ghci|     for_ greetings $ \greeting -> do
ghci|         print (greeting ++ " Stack Overflow!")
ghci| :}
"Hello Stack Overflow!"
"Bonjour Stack Overflow!"
"Hola Stack Overflow!"

sequenceA_ collapses a Foldable full of Applicative actions into a single action, ignoring the result.

ghci> let actions = [putStrLn "one", putStLn "two"]
ghci> sequenceA_ actions

traverse_ is defined as being equivalent to:

traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
traverse_ f = foldr (\x action -> f x *> action) (pure ())

sequenceA_ is defined as:

sequenceA_ :: (Foldable t, Applicative f) -> t (f a) -> f ()
sequenceA_ = traverse_ id

Moreover, when the Foldable is also a Functor, traverse_ and sequenceA_ have the following relationship:

traverse_ f = sequenceA_ . fmap f