Proposal: add indexed map and traverse to Data.List

David Feuer david.feuer at gmail.com
Sat Aug 17 06:16:36 UTC 2019


mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
mapWithIndex f = zipWith f [0..]

traverseWithIndex :: Applicative f => (Int -> a -> f b) -> [a] -> f [b]
traverseWithIndex f = sequenceA . mapWithIndex

The real implementation of mapWithIndex (and therefore of
traverseWithIndex) can be a "good consumer" for list fusion. mapWithIndex
can be a "good producer" as well (which the naive implementation already
accomplishes).

Similar functions (with these or similar names) are already common in
packages like vector, containers, unordered-containers, and primitive.

A more general function would merge zipping with unfolding:

zipWithUnfoldr :: (a -> b -> c) -> (s -> Maybe (b, s)) -> [a] -> s -> [c]
zipWithUnfoldr f g as s = zipWith f as (unfoldr g s)

But this doesn't seem like the friendliest or most obvious user interface,
so I am not proposing to add it to base.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/libraries/attachments/20190817/bdb6dd37/attachment.html>


More information about the Libraries mailing list