Map over list with running index
- georgOP 1
I couldn’t find any function that allows me to map over a list with the second argument for the function being the index of the element. In other languages this is sometimes known as
mapi. Is there anything like that in Daml?This is the implementation I came up with:
let mapi f l = zipWith f l [0 .. length l - 1]Can it be improved?
- cocreature 1
There isn’t anything builtin. The most efficient option is to roll it yourself:
mapWithIndex : (a -> Int -> b) -> [a] -> [b] mapWithIndex f as = fst $ foldr (\a (bs, i) -> (f a i :: bs, i + 1)) ([], 0) asAlternatively, I think your zipWith solution while less efficient is still pretty reasonable.
- Stephen
Just to play around with it a bit,
import Prelude hiding (mapA) import DA.Action.State import DA.Traversable mapI : Traversable t => (a -> Int -> b) -> t a -> t b mapI f xs = mapA (\a -> State \n -> (f a n, n + 1)) xs `evalState` 0