Fold with Data.Map.adjust

Viewed 97

I'm trying to get the correct function which will update one or multiple value by iterating over a list of key.

Example:

s1 = Data.Map.fromList [(1,"value1"), (2,"value2"), (3,"value3")]

By passing to the function the list [1,2] and the update value "plus", the list should look like this:

[(1,"plus"), (2,"plus"), (3,"value3")]

Here is what I tried so far, I'm having a hard time implementing the function which iterate over the list of key to update

changeValue map newValue xs = foldr (\k map -> Map.adjust (newValue)(xs)(sm)) map m

What should I look for from there? I don't think I could use map in this situation.

1 Answers

Okay, you're on the right track.

A fold is indeed what you need. You need to fold over the list of keys. The starting value is your original map, and it's being transformed during the fold.

You also correctly identified the function adjust.

adjust needs a function as the first argument. This function is \_ -> newValue, or just const newValue. I'd stay away using the name map, as it might cause confusion.

After these corrections, your program would probably look something like this:

import qualified Data.Map.Strict as M

s1 = M.fromList [(1,"value1"), (2,"value2"), (3,"value3")]

changeValue m newValue ks = foldr (\k m -> M.adjust (const newValue) k m) m ks

main :: IO ()
main = do
    print $ changeValue s1 "plus" [1, 2]
Related