Proposal: Add mapWithIndex to Data.List
Henning Thielemann
lemming at henning-thielemann.de
Sun Feb 1 08:39:24 UTC 2015
On Sat, 31 Jan 2015, David Feuer wrote:
> Vectors offer `imap` and sequences offer `mapWithIndex`. I think lists
> deserve to have something like this too. The obvious implementation,
> using `zipWith`, is unlikely to be the most efficient (because
> foldr/build fusion doesn't handle zips so wonderfully).
>
> To a first approximation:
>
> mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
> mapWithIndex f xs = build $ \c n ->
> let go x cont !i = f i x `c` cont (i+1)
> in foldr go (`seq` n) 0
It can also be written using Traversable. I have once written the
following more general function for this purpose:
zipWithTraversable ::
(Traversable f) => (a -> b -> c) -> Stream a -> f b -> f c
zipWithTraversable f as0 =
snd . mapAccumL (\(Stream.Cons a as) b -> (as, f a b)) as0
More information about the Libraries
mailing list