Reputation: 3
I need to change the value in a Map for several keys to a given value.
I have this code:
change :: Map.Map Integer Char -> [Integer] -> Char -> Map.Map Integer Char
change m ns c = foldr (\k mp -> Map.insert k c m) m ns
Only the first key in the list is changed. I can think other ways to do it but I'm trying to understand folds better.
Sorry, I've corrected the code.
Here's a ghci session:
*Maps> m
fromList [(3,'?'),(5,'?'),(7,'?'),(9,'?'),(11,'?'),(13,'?'),(15,'?'),(17,'?'),(19,'?'),(21,'?'),(23,'?'),(25,'?'),(27,'?'),(29,'?')]
it :: (Ord k, Num k, Enum k) => Map.Map k Char
(0.02 secs, 149,192 bytes)
*Maps> ns
[9,15,21,27]
it :: Num a => [a]
(0.00 secs, 59,000 bytes)
*Maps> change m ns 'c'
fromList [(3,'?'),(5,'?'),(7,'?'),(9,'c'),(11,'?'),(13,'?'),(15,'?'),(17,'?'),(19,'?'),(21,'?'),(23,'?'),(25,'?'),(27,'?'),(29,'?')]
it :: Map.Map Integer Char
(0.02 secs, 149,752 bytes)
Only the value for 9 is changed.
Upvotes: 0
Views: 798
Reputation: 1257
Your code does not compile for me; you sure you pasted it correctly? If I switch the parameters for the lambda:
change m ns c = foldr (\k mp -> Map.insert k c mp) m ns
or change the foldr to a foldl:
change m ns c = foldl (\mp k -> Map.insert k c mp) m ns
the code compiles (and inserts all the keys) both ways.
Upvotes: 1