on d1e2cb6 help sign in
patch/src/Data/AppendMap.hs
71 lines 2.2 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
5{-# LANGUAGE PatternSynonyms #-}
6{-# LANGUAGE RoleAnnotations #-}
7{-# LANGUAGE ScopedTypeVariables #-}
8{-# LANGUAGE TypeFamilies #-}
9{-# OPTIONS_GHC -fno-warn-orphans #-}
10-- | 'Data.Map' with a better 'Monoid' instance
11--
12-- 'Data.Map' has @mappend = union@, which is left-biased. AppendMap has
13-- @mappend = unionWith mappend@ instead.
14module Data.AppendMap
15 ( module Data.AppendMap
16 , module Data.Map.Monoidal
17 ) where
19import Prelude hiding (map, null)
21import Data.Coerce
22import Data.Default
23import Data.Map (Map)
24#if MIN_VERSION_containers(0,5,11)
25import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
26#else
27import qualified Data.Map as Map (showTree, showTreeWith)
28#endif
29import Data.Witherable (Filterable(..))
30import Data.Map.Monoidal (MonoidalMap(..), delete, null, empty)
31import qualified Data.Map.Monoidal as M
33{-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}
34type AppendMap = MonoidalMap
36{-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}
37_unAppendMap :: MonoidalMap k v -> Map k v
38_unAppendMap = getMonoidalMap
40pattern AppendMap :: Map k v -> MonoidalMap k v
41pattern AppendMap m = MonoidalMap m
43instance Filterable (MonoidalMap k) where
44 mapMaybe = M.mapMaybe
46-- | Deletes a key, returning 'Nothing' if the result is empty.
47nonEmptyDelete :: Ord k => k -> MonoidalMap k a -> Maybe (MonoidalMap k a)
48nonEmptyDelete k vs =
49 let deleted = delete k vs
50 in if null deleted
51 then Nothing
52 else Just deleted
54mapMaybeNoNull :: (a -> Maybe b)
55 -> MonoidalMap token a
56 -> Maybe (MonoidalMap token b)
57mapMaybeNoNull f as =
58 let bs = mapMaybe f as
59 in if null bs
60 then Nothing
61 else Just bs
63-- TODO: Move instances to `Reflex.Patch`
64showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String
65showTree = coerce (Map.showTree :: Map k a -> String)
67showTreeWith :: forall k a. (k -> a -> String) -> Bool -> Bool -> MonoidalMap k a -> String
68showTreeWith = coerce (Map.showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String)
70instance Default (MonoidalMap k a) where
71 def = empty