traverse
(“map with effects”)
Often we want to iterate through a collection of items, performing some effect for each item. This means we want some function that looks like
(a -> f b) -> t a -> resultwhere a -> f b is our effectful computation,
t a is our collection (typically a list or an array of
as) and result could take a few different
shapes depending on the requirements of our program, especially in the
common case when the effect f encapsulates some notion of
failure (like TaskEither in fp-ts, or anything
with ExceptT in its stack in Haskell).
A decision tree
-
Is there a notion of “partial” success (succeed with a
warning)?
-
Yes: Use
traversewithThese. - No: Continue.
-
Yes: Use
-
If everything succeeds, do you want to collect all
successes?
-
Yes:
-
…and in case of failure I want to report just the first
failure.
Use
traversewithEither/ExceptT. -
…and in case of failure I want to report all
failures.
Use
traversewithValidation.
-
…and in case of failure I want to report just the first
failure.
- No: Continue.
-
Yes:
-
Do you want just the first success (if anything
succeeds)?
-
Yes:
-
…and in case of failure I want to report just the last
failure.
Use
altAll/asum/choice/oneOfwithEither/ExceptT. -
…and in case of failure I want to report all
failures.
Use
altAll/asum/choice/oneOfwithValidation.
-
…and in case of failure I want to report just the last
failure.
- No: Continue.
-
Yes:
-
You want to just collect all successes and all
failures?
Use
wilt(orpartitionMapif the only “effect” is error handling).
wilt is from the Witherable type class in
PureScript and fp-ts, and appears as mapEitherA
in Haskell. Conceptually, “partitionMap with effects.” It’s
a rarer bird than traverse.