I would like to union two Map instances with a monadic function. This becomes a problem because of the unionWith type signature:
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
I'm looking for a smart way to do this. Here is my naive implementation:
monadicUnionWith :: (Monad m, Ord k) => (a -> a -> m a) -> Map k a -> Map k a -> m (Map k a)
monadicUnionWith f mapA mapB = do
let overlapping = toList $ intersectionWith (\a b -> (a,b)) mapA mapB
mergedOverlapping <- liftM fromList $ mapM helper overlapping
return $ union (union mergedOverlapping mapA) mapB
where
helper (k, (a,b)) = do
c <- f a b
return (k, c)
Note that union is left biased