Map over list with running index
App Development3 posts303 views2 likesLast activity Oct 2021
GE
georgOP
Oct 2021I 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?
CO
cocreature
Oct 2021There 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) as
Alternatively, I think your zipWith solution while less efficient is still pretty reasonable.
ST
Stephen
Oct 2021Just 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