An applicative version of merge.
mergeA takes two WhenMissing tactics, a WhenMatched
tactic and two maps. It uses the tactics to merge the maps.
Its behavior is best understood via its fundamental tactics,
traverseMaybeMissing and zipWithMaybeAMatched.
Behaves just like merge while allowing Applicative effects. Effects are
performed in increasing order of keys.
Consider
mergeA (traverseMaybeMissing g1)
(traverseMaybeMissing g2)
(zipWithMaybeAMatched f)
m1
m2
g1 k x = let z = if k == 2 then Just ("1" ++ x) else Nothing
in z <$ putStrLn ("g1 " ++ show (k, x))
g2 k x = let z = if k == 3 then Just ("2" ++ x) else Nothing
in z <$ putStrLn ("g2 " ++ show (k, x))
f k x y = let z = if k == 6 then Just ("3" ++ x ++ y) else Nothing
in z <$ putStrLn ("f " ++ show (k, x, y))
m1 = fromList [(2,"a"), (4,"b"), (6,"c"), (8,"d"), (10,"e"), (12,"f")]
m2 = fromList [(3,"g"), (6,"h"), (9,"i"), (12,"j")]
As with merge, the result map is [(2,"1a"), (3,"2g"), (6,"3ch")].
Additionally, g1, g2, and f perform IO effects, printing in
increasing order of key.
>>> mergeA (traverseMaybeMissing g1) (traverseMaybeMissing g2) (zipWithMaybeAMatched f) m1 m2
g1 (2,"a")
g2 (3,"g")
g1 (4,"b")
f (6,"c","h")
g1 (8,"d")
g2 (9,"i")
g1 (10,"e")
f (12,"f","j")
fromList [(2,"1a"),(3,"2g"),(6,"3ch")]
The other tactics below are optimizations or simplifications of
traverseMaybeMissing for special cases. Most importantly,
dropMissing drops all the keys.
preserveMissing leaves all the entries alone.
mapMaybeMissing does not use the Applicative context.
When mergeA is given three arguments, it is inlined at the call
site. To prevent excessive inlining, you should generally only use
mergeA to define custom combining functions.
Examples
data Pair a = Pair !a !a deriving Functor
instance Applicative Pair where
pure x = Pair x x
liftA2 f (Pair x1 y1) (Pair x2 y2) = Pair (f x1 x2) (f y1 y2)
-- | Calculate the left-biased union and intersection of two maps.
unionIntersection :: IntMap a -> IntMap a -> (IntMap a, IntMap a)
unionIntersection m1 m2 =
case mergeA preserveAndDropMissing preserveAndDropMissing preserveLeftMatched m1 m2 of
Pair mu mi -> (mu, mi)
where
-- use Pair to build the union and intersection together
preserveAndDropMissing = 'whenMissing' (\\_k x -> Pair (Just x) Nothing) (\\m -> Pair m empty)
preserveLeftMatched = 'zipWithMaybeAMatched' (\\_k x1 _x2 -> Pair (Just x1) (Just x1))
import Data.Functor.Const (Const(..))
import Data.Monoid (All(..))
-- | Whether the keys of the first map are a subset of the keys of the second map.
keysAreSubsetOf :: IntMap a -> IntMap b -> Bool
keysAreSubsetOf m1 m2 =
getAll (getConst (mergeA isEmpty 'dropMissing' 'dropMatched' m1 m2))
where
isEmpty = 'whenMissing' (\\_k _x -> Const (All False)) (\\m -> Const (All (null m)))
What to do with keys in m1 but not m2
What to do with keys in m2 but not m1
What to do with keys in both m1 and m2
Map m1
Map m2