In the code it works well as below
divide :: Int -> Int -> Either String Int
divide a 0 = Left "Error with 0"
divide a b = a / b
The code to be changed
Map.adjust (divide 3) "A" $ Map.fromList [("A",3),("B",0)]
The expected result should be :
Map.adjust (divide 3) "A" $ Map.fromList [("A",3),("B",0)]
=> Right $ Map.fromList [("A",1),("B",0)]
Map.adjust (divide 3) "B" $ Map.fromList [("A",3),("B",0)]
=> Left "Error with 0"
Or in general how to build a function like:
Map.adjust:: (a -> m b) -> k -> (Map k a) -> m (Map k b)
Thank you very much !
4
We can implement this by using insert
instead:
updateM :: (Ord k, Applicative m) => (a -> m a) -> k -> Map k a -> m (Map k a)
updateM f k map = case (map !? k) of
Just v -> flip (insert k) map <$> f v
_ -> pure map
We thus first check if the key exists, if so run f v
and then use that to insert the new value in the map
.