traverse -package:base-compat -package:case-insensitive package:relude

Map each element of a structure to an action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see traverse_.

Examples

Basic usage: In the first two examples we show each evaluated action mapping to the output structure.
>>> traverse Just [1,2,3,4]
Just [1,2,3,4]
>>> traverse id [Right 1, Right 2, Right 3, Right 4]
Right [1,2,3,4]
In the next examples, we show that Nothing and Left values short circuit the created structure.
>>> traverse (const Nothing) [1,2,3,4]
Nothing
>>> traverse (\x -> if odd x then Just x else Nothing)  [1,2,3,4]
Nothing
>>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]
Left 0
Maps a function that returns a value inside of an applicative functor over both elements of a tuple, with the entire tuple inside the applicative functor.
>>> traverseBoth (Just . ("Hello " <>)) ("Alice", "Bob")
Just ("Hello Alice","Hello Bob")

>>> traverseBoth (const Nothing) ("Alice", "Bob")
Nothing
Apply a function that returns a value inside of a functor, with the output in the first slot, the input in the second, and the entire tuple inside the functor. A dual to traverseToSnd
>>> traverseToFst (Just . (+1)) 10
Just (11,10)

>>> traverseToFst (const Nothing) 10
Nothing
Apply a function that returns a value inside of a functor, with the output in the second slot, the input in the first, and the entire tuple inside the functor. A dual to traverseToFst.
>>> traverseToSnd (Just . (+1)) 10
Just (10,11)

>>> traverseToSnd (const Nothing) 10
Nothing
Map each element of a structure to an Applicative action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see traverse. traverse_ is just like mapM_, but generalised to Applicative actions.

Examples

Basic usage:
>>> traverse_ print ["Hello", "world", "!"]
"Hello"
"world"
"!"
Evaluates the relevant functions at each element in the structure, running the action, and builds a new structure with the same shape, using the results produced from sequencing the actions.
bitraverse f g ≡ bisequenceA . bimap f g
For a version that ignores the results, see bitraverse_.

Examples

Basic usage:
>>> bitraverse listToMaybe (find odd) (Left [])
Nothing
>>> bitraverse listToMaybe (find odd) (Left [1, 2, 3])
Just (Left 1)
>>> bitraverse listToMaybe (find odd) (Right [4, 5])
Just (Right 5)
>>> bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])
Just (1,5)
>>> bitraverse listToMaybe (find odd) ([], [4, 5])
Nothing
Map each element of a structure using one of two actions, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results, see bitraverse.

Examples

Basic usage:
>>> bitraverse_ print (print . show) ("Hello", True)
"Hello"
"True"
>>> bitraverse_ print (print . show) (Right True)
"True"
>>> bitraverse_ print (print . show) (Left "Hello")
"Hello"