我想将两个Map实例与一个单子函数联合起来。由于unionWith
类型签名,这成为一个问题:
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
我正在寻找一种聪明的方法来做到这一点。这是我天真的实现:
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)
注意union
是左偏