haskell

scan on Map in Haskell


How can I run something like scanl on Map. Say I have Map.fromList [(0, 2), (1, 3), (2, 4)].

How can I get Map.fromList [(0, 2), (1, 5), (2, 9)] so that the values accumulated by summing in keys accending order?


Solution

  • The function I was referring to in my comment was mapAccum:

    mapAccum :: (a -> b -> (a, c)) -> a -> Map k b -> (a, Map k c)
    
    ghci> m = M.fromList [(0, 2), (1, 3), (2, 4)]
    ghci> M.mapAccum (\x y -> (x + y, x + y)) 0 m
    (9,fromList [(0,2),(1,5),(2,9)])
    

    It also returns the final accumulator, so if you don't want that you'll need to call snd on the resulting tuple.