This repository was archived by the owner on Oct 4, 2020. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +20
-2
lines changed Expand file tree Collapse file tree 3 files changed +20
-2
lines changed Original file line number Diff line number Diff line change 54
54
55
55
union :: forall k v. (P.Ord k) => Map k v -> Map k v -> Map k v
56
56
57
+ unionWith :: forall k v. (P.Ord k) => (v -> v -> v) -> Map k v -> Map k v -> Map k v
58
+
57
59
unions :: forall k v. (P.Ord k) => [Map k v] -> Map k v
58
60
59
61
update :: forall k v. (P.Ord k) => (v -> Maybe v) -> k -> Map k v -> Map k v
Original file line number Diff line number Diff line change @@ -22,6 +22,7 @@ module Data.Map
22
22
keys ,
23
23
values ,
24
24
union ,
25
+ unionWith ,
25
26
unions ,
26
27
map ,
27
28
size
@@ -230,8 +231,15 @@ values Leaf = []
230
231
values (Two left _ v right) = values left P .++ [v] P .++ values right
231
232
values (Three left _ v1 mid _ v2 right) = values left P .++ [v1] P .++ values mid P .++ [v2] P .++ values right
232
233
234
+ -- Computes the union of two maps, except that when a key exists in both maps, its value in the result
235
+ -- is computed by combining them with the supplied function.
236
+ unionWith :: forall k v . (P.Ord k ) => (v -> v -> v ) -> Map k v -> Map k v -> Map k v
237
+ unionWith f m1 m2 = foldl go m2 (toList m1)
238
+ where
239
+ go m (Tuple k v) = alter (Just P .<<< maybe v (f v)) k m
240
+
233
241
union :: forall k v . (P.Ord k ) => Map k v -> Map k v -> Map k v
234
- union m1 m2 = foldl (\m ( Tuple k v) -> insert k v m) m2 (toList m1)
242
+ union = unionWith P .const
235
243
236
244
unions :: forall k v . (P.Ord k ) => [Map k v ] -> Map k v
237
245
unions = foldl union empty
Original file line number Diff line number Diff line change @@ -6,7 +6,7 @@ import Data.Maybe
6
6
import Data.Tuple
7
7
import Data.Array (map , length , nubBy )
8
8
import Data.Function (on )
9
- import Data.Foldable (foldl )
9
+ import Data.Foldable (foldl , for_ )
10
10
11
11
import Test.QuickCheck
12
12
@@ -166,6 +166,14 @@ mapTests = do
166
166
trace " Union is idempotent"
167
167
quickCheck $ \m1 m2 -> (m1 `M.union` m2) == ((m1 `M.union` m2) `M.union` (m2 :: M.Map SmallKey Number ))
168
168
169
+ trace " unionWith"
170
+ for_ [Tuple (+) 0 , Tuple (*) 1 ] $ \(Tuple op ident) ->
171
+ quickCheck $ \m1 m2 k ->
172
+ let u = M .unionWith op m1 m2 :: M.Map SmallKey Number
173
+ in case M .lookup k u of
174
+ Nothing -> not (M .member k m1 || M .member k m2)
175
+ Just v -> v == op (fromMaybe ident (M .lookup k m1)) (fromMaybe ident (M .lookup k m2))
176
+
169
177
trace " size"
170
178
quickCheck $ \xs ->
171
179
let xs' = nubBy ((==) `on` fst) xs
You can’t perform that action at this time.
0 commit comments