@@ -7,15 +7,19 @@ module Unison.Util.Map
7
7
deleteLookup ,
8
8
deleteLookupJust ,
9
9
elemsSet ,
10
+ foldKeysCommutative ,
11
+ foldValuesCommutative ,
10
12
foldM ,
11
13
foldMapM ,
12
14
for_ ,
15
+ fromSetA ,
13
16
insertLookup ,
14
17
invert ,
15
18
lookupJust ,
16
19
mergeMap ,
17
20
unionWithM ,
18
21
remap ,
22
+ thenInsertPair ,
19
23
traverseKeys ,
20
24
traverseKeysWith ,
21
25
swap ,
@@ -36,6 +40,7 @@ import Data.Map.Internal qualified as Map (Map (Bin, Tip))
36
40
import Data.Map.Merge.Strict qualified as Map
37
41
import Data.Map.Strict qualified as Map
38
42
import Data.Set qualified as Set
43
+ import Data.Set.Internal qualified as Set (Set (.. ))
39
44
import Data.These (These (.. ))
40
45
import Data.Vector (Vector )
41
46
import Data.Vector qualified as Vector
@@ -123,6 +128,26 @@ elemsSet :: (Ord v) => Map k v -> Set v
123
128
elemsSet =
124
129
Set. fromList . Map. elems
125
130
131
+ -- | Fold the keys of a map strictly with a "commutative" combining function that doesn't receive the elements in any
132
+ -- particular order.
133
+ foldKeysCommutative :: (k -> acc -> acc ) -> acc -> Map k v -> acc
134
+ foldKeysCommutative f =
135
+ let go ! acc = \ case
136
+ Map. Bin _ k _ l r : xs -> go (f k acc) (l : r : xs)
137
+ Map. Tip : xs -> go acc xs
138
+ [] -> acc
139
+ in \ z xs -> go z [xs]
140
+
141
+ -- | Fold the values of a map strictly with a "commutative" combining function that doesn't receive the elements in any
142
+ -- particular order.
143
+ foldValuesCommutative :: (v -> acc -> acc ) -> acc -> Map k v -> acc
144
+ foldValuesCommutative f =
145
+ let go ! acc = \ case
146
+ Map. Bin _ _ v l r : xs -> go (f v acc) (l : r : xs)
147
+ Map. Tip : xs -> go acc xs
148
+ [] -> acc
149
+ in \ z xs -> go z [xs]
150
+
126
151
-- | Like 'Map.foldlWithKey'', but with a monadic accumulator.
127
152
foldM :: (Monad m ) => (acc -> k -> v -> m acc ) -> acc -> Map k v -> m acc
128
153
foldM f acc0 =
@@ -158,6 +183,15 @@ for_ m f =
158
183
f k v
159
184
go ys
160
185
186
+ -- | Like 'Map.fromSet', but in an applicative functor.
187
+ fromSetA :: (Applicative m ) => (k -> m a ) -> Set k -> m (Map k a )
188
+ fromSetA f =
189
+ go
190
+ where
191
+ go = \ case
192
+ Set. Tip -> pure Map. Tip
193
+ Set. Bin n k l r -> (\ v l' r' -> Map. Bin n k v l' r') <$> f k <*> go l <*> go r
194
+
161
195
unionWithM ::
162
196
forall m k a .
163
197
(Monad m , Ord k ) =>
@@ -182,6 +216,11 @@ remap :: (Ord k1) => ((k0, v0) -> (k1, v1)) -> Map k0 v0 -> Map k1 v1
182
216
remap f =
183
217
Map. fromList . map f . Map. toList
184
218
219
+ -- | Insert a pair in postfix-style.
220
+ thenInsertPair :: (Ord k ) => Map k v -> (k , v ) -> Map k v
221
+ thenInsertPair m (k, v) =
222
+ Map. insert k v m
223
+
185
224
traverseKeys :: (Applicative f , Ord k' ) => (k -> f k' ) -> Map k v -> f (Map k' v )
186
225
traverseKeys f = bitraverse f pure
187
226
0 commit comments