Improve {Map,IntMap}.intersection* and its tests.
[packages/containers.git] / Data / Map / Strict.hs
1 {-# LANGUAGE CPP #-}
2 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
3 {-# LANGUAGE Safe #-}
4 #endif
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module : Data.Map.Strict
8 -- Copyright : (c) Daan Leijen 2002
9 -- (c) Andriy Palamarchuk 2008
10 -- License : BSD-style
11 -- Maintainer : libraries@haskell.org
12 -- Stability : provisional
13 -- Portability : portable
14 --
15 -- An efficient implementation of ordered maps from keys to values
16 -- (dictionaries).
17 --
18 -- API of this module is strict in both the keys and the values.
19 -- If you need value-lazy maps, use 'Data.Map.Lazy' instead.
20 -- The 'Map' type is shared between the lazy and strict modules,
21 -- meaning that the same 'Map' value can be passed to functions in
22 -- both modules (although that is rarely needed).
23 --
24 -- These modules are intended to be imported qualified, to avoid name
25 -- clashes with Prelude functions, e.g.
26 --
27 -- > import qualified Data.Map.Strict as Map
28 --
29 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
30 -- trees of /bounded balance/) as described by:
31 --
32 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
33 -- Journal of Functional Programming 3(4):553-562, October 1993,
34 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
35 --
36 -- * J. Nievergelt and E.M. Reingold,
37 -- \"/Binary search trees of bounded balance/\",
38 -- SIAM journal of computing 2(1), March 1973.
39 --
40 -- Note that the implementation is /left-biased/ -- the elements of a
41 -- first argument are always preferred to the second, for example in
42 -- 'union' or 'insert'.
43 --
44 -- Operation comments contain the operation time complexity in
45 -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
46 --
47 -- Be aware that the 'Functor', 'Traversable' and 'Data' instances
48 -- are the same as for the 'Data.Map.Lazy' module, so if they are used
49 -- on strict maps, the resulting maps will be lazy.
50 -----------------------------------------------------------------------------
51
52 -- It is crucial to the performance that the functions specialize on the Ord
53 -- type when possible. GHC 7.0 and higher does this by itself when it sees th
54 -- unfolding of a function -- that is why all public functions are marked
55 -- INLINABLE (that exposes the unfolding).
56 --
57 -- For other compilers and GHC pre 7.0, we mark some of the functions INLINE.
58 -- We mark the functions that just navigate down the tree (lookup, insert,
59 -- delete and similar). That navigation code gets inlined and thus specialized
60 -- when possible. There is a price to pay -- code growth. The code INLINED is
61 -- therefore only the tree navigation, all the real work (rebalancing) is not
62 -- INLINED by using a NOINLINE.
63 --
64 -- All methods that can be INLINE are not recursive -- a 'go' function doing
65 -- the real work is provided.
66
67 module Data.Map.Strict
68 (
69 -- * Strictness properties
70 -- $strictness
71
72 -- * Map type
73 #if !defined(TESTING)
74 Map -- instance Eq,Show,Read
75 #else
76 Map(..) -- instance Eq,Show,Read
77 #endif
78
79 -- * Operators
80 , (!), (\\)
81
82 -- * Query
83 , null
84 , size
85 , member
86 , notMember
87 , lookup
88 , findWithDefault
89
90 -- * Construction
91 , empty
92 , singleton
93
94 -- ** Insertion
95 , insert
96 , insertWith
97 , insertWithKey
98 , insertLookupWithKey
99
100 -- ** Delete\/Update
101 , delete
102 , adjust
103 , adjustWithKey
104 , update
105 , updateWithKey
106 , updateLookupWithKey
107 , alter
108
109 -- * Combine
110
111 -- ** Union
112 , union
113 , unionWith
114 , unionWithKey
115 , unions
116 , unionsWith
117
118 -- ** Difference
119 , difference
120 , differenceWith
121 , differenceWithKey
122
123 -- ** Intersection
124 , intersection
125 , intersectionWith
126 , intersectionWithKey
127
128 -- * Traversal
129 -- ** Map
130 , map
131 , mapWithKey
132 , mapAccum
133 , mapAccumWithKey
134 , mapAccumRWithKey
135 , mapKeys
136 , mapKeysWith
137 , mapKeysMonotonic
138
139 -- * Folds
140 , foldr
141 , foldl
142 , foldrWithKey
143 , foldlWithKey
144 -- ** Strict folds
145 , foldr'
146 , foldl'
147 , foldrWithKey'
148 , foldlWithKey'
149
150 -- * Conversion
151 , elems
152 , keys
153 , keysSet
154 , assocs
155
156 -- ** Lists
157 , toList
158 , fromList
159 , fromListWith
160 , fromListWithKey
161
162 -- ** Ordered lists
163 , toAscList
164 , toDescList
165 , fromAscList
166 , fromAscListWith
167 , fromAscListWithKey
168 , fromDistinctAscList
169
170 -- * Filter
171 , filter
172 , filterWithKey
173 , partition
174 , partitionWithKey
175
176 , mapMaybe
177 , mapMaybeWithKey
178 , mapEither
179 , mapEitherWithKey
180
181 , split
182 , splitLookup
183
184 -- * Submap
185 , isSubmapOf, isSubmapOfBy
186 , isProperSubmapOf, isProperSubmapOfBy
187
188 -- * Indexed
189 , lookupIndex
190 , findIndex
191 , elemAt
192 , updateAt
193 , deleteAt
194
195 -- * Min\/Max
196 , findMin
197 , findMax
198 , deleteMin
199 , deleteMax
200 , deleteFindMin
201 , deleteFindMax
202 , updateMin
203 , updateMax
204 , updateMinWithKey
205 , updateMaxWithKey
206 , minView
207 , maxView
208 , minViewWithKey
209 , maxViewWithKey
210
211 -- * Debugging
212 , showTree
213 , showTreeWith
214 , valid
215
216 #if defined(TESTING)
217 -- * Internals
218 , bin
219 , balanced
220 , join
221 , merge
222 #endif
223 ) where
224
225 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
226
227 import Data.Map.Base hiding
228 ( findWithDefault
229 , singleton
230 , insert
231 , insertWith
232 , insertWithKey
233 , insertLookupWithKey
234 , adjust
235 , adjustWithKey
236 , update
237 , updateWithKey
238 , updateLookupWithKey
239 , alter
240 , unionWith
241 , unionWithKey
242 , unionsWith
243 , differenceWith
244 , differenceWithKey
245 , intersectionWith
246 , intersectionWithKey
247 , map
248 , mapWithKey
249 , mapAccum
250 , mapAccumWithKey
251 , mapAccumRWithKey
252 , mapKeysWith
253 , fromList
254 , fromListWith
255 , fromListWithKey
256 , fromAscList
257 , fromAscListWith
258 , fromAscListWithKey
259 , fromDistinctAscList
260 , mapMaybe
261 , mapMaybeWithKey
262 , mapEither
263 , mapEitherWithKey
264 , updateAt
265 , updateMin
266 , updateMax
267 , updateMinWithKey
268 , updateMaxWithKey
269 )
270 import Data.StrictPair
271
272 -- Use macros to define strictness of functions. STRICT_x_OF_y
273 -- denotes an y-ary function strict in the x-th parameter. Similarly
274 -- STRICT_x_y_OF_z denotes an z-ary function strict in the x-th and
275 -- y-th parameter. We do not use BangPatterns, because they are not
276 -- in any standard and we want the compilers to be compiled by as many
277 -- compilers as possible.
278 #define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
279 #define STRICT_1_2_OF_3(fn) fn arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
280 #define STRICT_2_3_OF_4(fn) fn _ arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
281
282 -- $strictness
283 --
284 -- This module satisfies the following strictness properties:
285 --
286 -- 1. Key and value arguments are evaluated to WHNF;
287 --
288 -- 2. Keys and values are evaluated to WHNF before they are stored in
289 -- the map.
290 --
291 -- Here are some examples that illustrate the first property:
292 --
293 -- > insertWith (\ new old -> old) k undefined m == undefined
294 -- > delete undefined m == undefined
295 --
296 -- Here are some examples that illustrate the second property:
297 --
298 -- > map (\ v -> undefined) m == undefined -- m is not empty
299 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
300
301 {--------------------------------------------------------------------
302 Query
303 --------------------------------------------------------------------}
304
305 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
306 -- the value at key @k@ or returns default value @def@
307 -- when the key is not in the map.
308 --
309 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
310 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
311
312 findWithDefault :: Ord k => a -> k -> Map k a -> a
313 findWithDefault def k m = def `seq` case lookup k m of
314 Nothing -> def
315 Just x -> x
316 #if __GLASGOW_HASKELL__ >= 700
317 {-# INLINABLE findWithDefault #-}
318 #else
319 {-# INLINE findWithDefault #-}
320 #endif
321
322 {--------------------------------------------------------------------
323 Construction
324 --------------------------------------------------------------------}
325
326 -- | /O(1)/. A map with a single element.
327 --
328 -- > singleton 1 'a' == fromList [(1, 'a')]
329 -- > size (singleton 1 'a') == 1
330
331 singleton :: k -> a -> Map k a
332 singleton k x = x `seq` Bin 1 k x Tip Tip
333 {-# INLINE singleton #-}
334
335 {--------------------------------------------------------------------
336 Insertion
337 --------------------------------------------------------------------}
338 -- | /O(log n)/. Insert a new key and value in the map.
339 -- If the key is already present in the map, the associated value is
340 -- replaced with the supplied value. 'insert' is equivalent to
341 -- @'insertWith' 'const'@.
342 --
343 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
344 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
345 -- > insert 5 'x' empty == singleton 5 'x'
346
347 insert :: Ord k => k -> a -> Map k a -> Map k a
348 insert = go
349 where
350 STRICT_1_2_OF_3(go)
351 go kx x Tip = singleton kx x
352 go kx x (Bin sz ky y l r) =
353 case compare kx ky of
354 LT -> balanceL ky y (go kx x l) r
355 GT -> balanceR ky y l (go kx x r)
356 EQ -> Bin sz kx x l r
357 #if __GLASGOW_HASKELL__ >= 700
358 {-# INLINABLE insert #-}
359 #else
360 {-# INLINE insert #-}
361 #endif
362
363 -- | /O(log n)/. Insert with a function, combining new value and old value.
364 -- @'insertWith' f key value mp@
365 -- will insert the pair (key, value) into @mp@ if key does
366 -- not exist in the map. If the key does exist, the function will
367 -- insert the pair @(key, f new_value old_value)@.
368 --
369 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
370 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
371 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
372
373 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
374 insertWith f = insertWithKey (\_ x' y' -> f x' y')
375 #if __GLASGOW_HASKELL__ >= 700
376 {-# INLINABLE insertWith #-}
377 #else
378 {-# INLINE insertWith #-}
379 #endif
380
381 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
382 -- @'insertWithKey' f key value mp@
383 -- will insert the pair (key, value) into @mp@ if key does
384 -- not exist in the map. If the key does exist, the function will
385 -- insert the pair @(key,f key new_value old_value)@.
386 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
387 --
388 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
389 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
390 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
391 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
392
393 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
394 insertWithKey = go
395 where
396 STRICT_2_3_OF_4(go)
397 go _ kx x Tip = singleton kx x
398 go f kx x (Bin sy ky y l r) =
399 case compare kx ky of
400 LT -> balanceL ky y (go f kx x l) r
401 GT -> balanceR ky y l (go f kx x r)
402 EQ -> let x' = f kx x y
403 in x' `seq` Bin sy kx x' l r
404 #if __GLASGOW_HASKELL__ >= 700
405 {-# INLINABLE insertWithKey #-}
406 #else
407 {-# INLINE insertWithKey #-}
408 #endif
409
410 -- | /O(log n)/. Combines insert operation with old value retrieval.
411 -- The expression (@'insertLookupWithKey' f k x map@)
412 -- is a pair where the first element is equal to (@'lookup' k map@)
413 -- and the second element equal to (@'insertWithKey' f k x map@).
414 --
415 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
416 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
417 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
418 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
419 --
420 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
421 --
422 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
423 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
424 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
425
426 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
427 -> (Maybe a, Map k a)
428 insertLookupWithKey = go
429 where
430 STRICT_2_3_OF_4(go)
431 go _ kx x Tip = Nothing `strictPair` singleton kx x
432 go f kx x (Bin sy ky y l r) =
433 case compare kx ky of
434 LT -> let (found, l') = go f kx x l
435 in found `strictPair` balanceL ky y l' r
436 GT -> let (found, r') = go f kx x r
437 in found `strictPair` balanceR ky y l r'
438 EQ -> let x' = f kx x y
439 in x' `seq` (Just y `strictPair` Bin sy kx x' l r)
440 #if __GLASGOW_HASKELL__ >= 700
441 {-# INLINABLE insertLookupWithKey #-}
442 #else
443 {-# INLINE insertLookupWithKey #-}
444 #endif
445
446 {--------------------------------------------------------------------
447 Deletion
448 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
449 --------------------------------------------------------------------}
450
451 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
452 -- When the key is not
453 -- a member of the map, the original map is returned.
454 --
455 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
456 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
457 -- > adjust ("new " ++) 7 empty == empty
458
459 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
460 adjust f = adjustWithKey (\_ x -> f x)
461 #if __GLASGOW_HASKELL__ >= 700
462 {-# INLINABLE adjust #-}
463 #else
464 {-# INLINE adjust #-}
465 #endif
466
467 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
468 -- a member of the map, the original map is returned.
469 --
470 -- > let f key x = (show key) ++ ":new " ++ x
471 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
472 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
473 -- > adjustWithKey f 7 empty == empty
474
475 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
476 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
477 #if __GLASGOW_HASKELL__ >= 700
478 {-# INLINABLE adjustWithKey #-}
479 #else
480 {-# INLINE adjustWithKey #-}
481 #endif
482
483 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
484 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
485 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
486 --
487 -- > let f x = if x == "a" then Just "new a" else Nothing
488 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
489 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
490 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
491
492 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
493 update f = updateWithKey (\_ x -> f x)
494 #if __GLASGOW_HASKELL__ >= 700
495 {-# INLINABLE update #-}
496 #else
497 {-# INLINE update #-}
498 #endif
499
500 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
501 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
502 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
503 -- to the new value @y@.
504 --
505 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
506 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
507 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
508 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
509
510 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
511 updateWithKey = go
512 where
513 STRICT_2_OF_3(go)
514 go _ _ Tip = Tip
515 go f k(Bin sx kx x l r) =
516 case compare k kx of
517 LT -> balanceR kx x (go f k l) r
518 GT -> balanceL kx x l (go f k r)
519 EQ -> case f kx x of
520 Just x' -> x' `seq` Bin sx kx x' l r
521 Nothing -> glue l r
522 #if __GLASGOW_HASKELL__ >= 700
523 {-# INLINABLE updateWithKey #-}
524 #else
525 {-# INLINE updateWithKey #-}
526 #endif
527
528 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
529 -- The function returns changed value, if it is updated.
530 -- Returns the original key value if the map entry is deleted.
531 --
532 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
533 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
534 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
535 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
536
537 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
538 updateLookupWithKey = go
539 where
540 STRICT_2_OF_3(go)
541 go _ _ Tip = (Nothing,Tip)
542 go f k (Bin sx kx x l r) =
543 case compare k kx of
544 LT -> let (found,l') = go f k l
545 in found `strictPair` balanceR kx x l' r
546 GT -> let (found,r') = go f k r
547 in found `strictPair` balanceL kx x l r'
548 EQ -> case f kx x of
549 Just x' -> x' `seq` (Just x' `strictPair` Bin sx kx x' l r)
550 Nothing -> (Just x,glue l r)
551 #if __GLASGOW_HASKELL__ >= 700
552 {-# INLINABLE updateLookupWithKey #-}
553 #else
554 {-# INLINE updateLookupWithKey #-}
555 #endif
556
557 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
558 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
559 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
560 --
561 -- > let f _ = Nothing
562 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
563 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
564 -- >
565 -- > let f _ = Just "c"
566 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
567 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
568
569 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
570 alter = go
571 where
572 STRICT_2_OF_3(go)
573 go f k Tip = case f Nothing of
574 Nothing -> Tip
575 Just x -> singleton k x
576
577 go f k (Bin sx kx x l r) = case compare k kx of
578 LT -> balance kx x (go f k l) r
579 GT -> balance kx x l (go f k r)
580 EQ -> case f (Just x) of
581 Just x' -> x' `seq` Bin sx kx x' l r
582 Nothing -> glue l r
583 #if __GLASGOW_HASKELL__ >= 700
584 {-# INLINABLE alter #-}
585 #else
586 {-# INLINE alter #-}
587 #endif
588
589 {--------------------------------------------------------------------
590 Indexing
591 --------------------------------------------------------------------}
592
593 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
594 -- invalid index is used.
595 --
596 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
597 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
598 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
599 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
600 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
601 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
602 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
603 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
604
605 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
606 updateAt f i t = i `seq`
607 case t of
608 Tip -> error "Map.updateAt: index out of range"
609 Bin sx kx x l r -> case compare i sizeL of
610 LT -> balanceR kx x (updateAt f i l) r
611 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
612 EQ -> case f kx x of
613 Just x' -> x' `seq` Bin sx kx x' l r
614 Nothing -> glue l r
615 where
616 sizeL = size l
617
618 {--------------------------------------------------------------------
619 Minimal, Maximal
620 --------------------------------------------------------------------}
621
622 -- | /O(log n)/. Update the value at the minimal key.
623 --
624 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
625 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
626
627 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
628 updateMin f m
629 = updateMinWithKey (\_ x -> f x) m
630
631 -- | /O(log n)/. Update the value at the maximal key.
632 --
633 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
634 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
635
636 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
637 updateMax f m
638 = updateMaxWithKey (\_ x -> f x) m
639
640
641 -- | /O(log n)/. Update the value at the minimal key.
642 --
643 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
644 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
645
646 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
647 updateMinWithKey _ Tip = Tip
648 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
649 Nothing -> r
650 Just x' -> x' `seq` Bin sx kx x' Tip r
651 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
652
653 -- | /O(log n)/. Update the value at the maximal key.
654 --
655 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
656 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
657
658 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
659 updateMaxWithKey _ Tip = Tip
660 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
661 Nothing -> l
662 Just x' -> x' `seq` Bin sx kx x' l Tip
663 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
664
665 {--------------------------------------------------------------------
666 Union.
667 --------------------------------------------------------------------}
668
669 -- | The union of a list of maps, with a combining operation:
670 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
671 --
672 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
673 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
674
675 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
676 unionsWith f ts
677 = foldlStrict (unionWith f) empty ts
678 #if __GLASGOW_HASKELL__ >= 700
679 {-# INLINABLE unionsWith #-}
680 #endif
681
682 {--------------------------------------------------------------------
683 Union with a combining function
684 --------------------------------------------------------------------}
685 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
686 --
687 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
688
689 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
690 unionWith f m1 m2
691 = unionWithKey (\_ x y -> f x y) m1 m2
692 #if __GLASGOW_HASKELL__ >= 700
693 {-# INLINABLE unionWith #-}
694 #endif
695
696 -- | /O(n+m)/.
697 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
698 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
699 --
700 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
701 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
702
703 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
704 unionWithKey _ Tip t2 = t2
705 unionWithKey _ t1 Tip = t1
706 unionWithKey f t1 t2 = hedgeUnionWithKey f NothingS NothingS t1 t2
707 #if __GLASGOW_HASKELL__ >= 700
708 {-# INLINABLE unionWithKey #-}
709 #endif
710
711 hedgeUnionWithKey :: Ord a
712 => (a -> b -> b -> b)
713 -> MaybeS a -> MaybeS a
714 -> Map a b -> Map a b
715 -> Map a b
716 hedgeUnionWithKey _ _ _ t1 Tip
717 = t1
718 hedgeUnionWithKey _ blo bhi Tip (Bin _ kx x l r)
719 = join kx x (filterGt blo l) (filterLt bhi r)
720 hedgeUnionWithKey f blo bhi (Bin _ kx x l r) t2
721 = newx `seq` join kx newx (hedgeUnionWithKey f blo bmi l lt)
722 (hedgeUnionWithKey f bmi bhi r gt)
723 where
724 bmi = JustS kx
725 lt = trim blo bmi t2
726 (found,gt) = trimLookupLo kx bhi t2
727 newx = case found of
728 Nothing -> x
729 Just (_,y) -> f kx x y
730 #if __GLASGOW_HASKELL__ >= 700
731 {-# INLINABLE hedgeUnionWithKey #-}
732 #endif
733
734 {--------------------------------------------------------------------
735 Difference
736 --------------------------------------------------------------------}
737
738 -- | /O(n+m)/. Difference with a combining function.
739 -- When two equal keys are
740 -- encountered, the combining function is applied to the values of these keys.
741 -- If it returns 'Nothing', the element is discarded (proper set difference). If
742 -- it returns (@'Just' y@), the element is updated with a new value @y@.
743 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
744 --
745 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
746 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
747 -- > == singleton 3 "b:B"
748
749 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
750 differenceWith f m1 m2
751 = differenceWithKey (\_ x y -> f x y) m1 m2
752 #if __GLASGOW_HASKELL__ >= 700
753 {-# INLINABLE differenceWith #-}
754 #endif
755
756 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
757 -- encountered, the combining function is applied to the key and both values.
758 -- If it returns 'Nothing', the element is discarded (proper set difference). If
759 -- it returns (@'Just' y@), the element is updated with a new value @y@.
760 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
761 --
762 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
763 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
764 -- > == singleton 3 "3:b|B"
765
766 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
767 differenceWithKey _ Tip _ = Tip
768 differenceWithKey _ t1 Tip = t1
769 differenceWithKey f t1 t2 = hedgeDiffWithKey f NothingS NothingS t1 t2
770 #if __GLASGOW_HASKELL__ >= 700
771 {-# INLINABLE differenceWithKey #-}
772 #endif
773
774 hedgeDiffWithKey :: Ord a
775 => (a -> b -> c -> Maybe b)
776 -> MaybeS a -> MaybeS a
777 -> Map a b -> Map a c
778 -> Map a b
779 hedgeDiffWithKey _ _ _ Tip _
780 = Tip
781 hedgeDiffWithKey _ blo bhi (Bin _ kx x l r) Tip
782 = join kx x (filterGt blo l) (filterLt bhi r)
783 hedgeDiffWithKey f blo bhi t (Bin _ kx x l r)
784 = case found of
785 Nothing -> merge tl tr
786 Just (ky,y) ->
787 case f ky y x of
788 Nothing -> merge tl tr
789 Just z -> z `seq` join ky z tl tr
790 where
791 bmi = JustS kx
792 lt = trim blo bmi t
793 (found,gt) = trimLookupLo kx bhi t
794 tl = hedgeDiffWithKey f blo bmi lt l
795 tr = hedgeDiffWithKey f bmi bhi gt r
796 #if __GLASGOW_HASKELL__ >= 700
797 {-# INLINABLE hedgeDiffWithKey #-}
798 #endif
799
800 {--------------------------------------------------------------------
801 Intersection
802 --------------------------------------------------------------------}
803
804 -- | /O(n+m)/. Intersection with a combining function.
805 --
806 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
807
808 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
809 intersectionWith f m1 m2
810 = intersectionWithKey (\_ x y -> f x y) m1 m2
811 #if __GLASGOW_HASKELL__ >= 700
812 {-# INLINABLE intersectionWith #-}
813 #endif
814
815 -- | /O(n+m)/. Intersection with a combining function.
816 -- Intersection is more efficient on (bigset \``intersection`\` smallset).
817 --
818 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
819 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
820
821
822 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
823 intersectionWithKey _ Tip _ = Tip
824 intersectionWithKey _ _ Tip = Tip
825 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
826 if s1 >= s2 then
827 case splitLookupWithKey k2 t1 of
828 (lt, Just (k, x), gt) -> case f k x x2 of x' -> x' `seq` join k x' (intersectionWithKey f lt l2) (intersectionWithKey f gt r2)
829 (lt, Nothing, gt) -> merge (intersectionWithKey f lt l2) (intersectionWithKey f gt r2)
830 else
831 case splitLookup k1 t2 of
832 (lt, Just x, gt) -> case f k1 x1 x of x' -> x' `seq` join k1 x' (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
833 (lt, Nothing, gt) -> merge (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
834 #if __GLASGOW_HASKELL__ >= 700
835 {-# INLINABLE intersectionWithKey #-}
836 #endif
837
838 {--------------------------------------------------------------------
839 Filter and partition
840 --------------------------------------------------------------------}
841
842 -- | /O(n)/. Map values and collect the 'Just' results.
843 --
844 -- > let f x = if x == "a" then Just "new a" else Nothing
845 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
846
847 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
848 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
849
850 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
851 --
852 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
853 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
854
855 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
856 mapMaybeWithKey _ Tip = Tip
857 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
858 Just y -> y `seq` join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
859 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
860
861 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
862 --
863 -- > let f a = if a < "c" then Left a else Right a
864 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
865 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
866 -- >
867 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
868 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
869
870 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
871 mapEither f m
872 = mapEitherWithKey (\_ x -> f x) m
873
874 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
875 --
876 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
877 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
878 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
879 -- >
880 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
881 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
882
883 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
884 mapEitherWithKey _ Tip = (Tip, Tip)
885 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
886 Left y -> y `seq` (join kx y l1 r1 `strictPair` merge l2 r2)
887 Right z -> z `seq` (merge l1 r1 `strictPair` join kx z l2 r2)
888 where
889 (l1,l2) = mapEitherWithKey f l
890 (r1,r2) = mapEitherWithKey f r
891
892 {--------------------------------------------------------------------
893 Mapping
894 --------------------------------------------------------------------}
895 -- | /O(n)/. Map a function over all values in the map.
896 --
897 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
898
899 map :: (a -> b) -> Map k a -> Map k b
900 map f = mapWithKey (\_ x -> f x)
901
902 -- | /O(n)/. Map a function over all values in the map.
903 --
904 -- > let f key x = (show key) ++ ":" ++ x
905 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
906
907 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
908 mapWithKey _ Tip = Tip
909 mapWithKey f (Bin sx kx x l r) = let x' = f kx x
910 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
911
912 -- | /O(n)/. The function 'mapAccum' threads an accumulating
913 -- argument through the map in ascending order of keys.
914 --
915 -- > let f a b = (a ++ b, b ++ "X")
916 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
917
918 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
919 mapAccum f a m
920 = mapAccumWithKey (\a' _ x' -> f a' x') a m
921
922 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
923 -- argument through the map in ascending order of keys.
924 --
925 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
926 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
927
928 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
929 mapAccumWithKey f a t
930 = mapAccumL f a t
931
932 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
933 -- argument through the map in ascending order of keys.
934 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
935 mapAccumL _ a Tip = (a,Tip)
936 mapAccumL f a (Bin sx kx x l r) =
937 let (a1,l') = mapAccumL f a l
938 (a2,x') = f a1 kx x
939 (a3,r') = mapAccumL f a2 r
940 in x' `seq` (a3,Bin sx kx x' l' r')
941
942 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
943 -- argument through the map in descending order of keys.
944 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
945 mapAccumRWithKey _ a Tip = (a,Tip)
946 mapAccumRWithKey f a (Bin sx kx x l r) =
947 let (a1,r') = mapAccumRWithKey f a r
948 (a2,x') = f a1 kx x
949 (a3,l') = mapAccumRWithKey f a2 l
950 in x' `seq` (a3,Bin sx kx x' l' r')
951
952 -- | /O(n*log n)/.
953 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
954 --
955 -- The size of the result may be smaller if @f@ maps two or more distinct
956 -- keys to the same new key. In this case the associated values will be
957 -- combined using @c@.
958 --
959 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
960 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
961
962 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
963 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
964 #if __GLASGOW_HASKELL__ >= 700
965 {-# INLINABLE mapKeysWith #-}
966 #endif
967
968 {--------------------------------------------------------------------
969 Lists
970 use [foldlStrict] to reduce demand on the control-stack
971 --------------------------------------------------------------------}
972 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
973 -- If the list contains more than one value for the same key, the last value
974 -- for the key is retained.
975 --
976 -- > fromList [] == empty
977 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
978 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
979
980 fromList :: Ord k => [(k,a)] -> Map k a
981 fromList xs
982 = foldlStrict ins empty xs
983 where
984 ins t (k,x) = insert k x t
985 #if __GLASGOW_HASKELL__ >= 700
986 {-# INLINABLE fromList #-}
987 #endif
988
989 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
990 --
991 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
992 -- > fromListWith (++) [] == empty
993
994 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
995 fromListWith f xs
996 = fromListWithKey (\_ x y -> f x y) xs
997 #if __GLASGOW_HASKELL__ >= 700
998 {-# INLINABLE fromListWith #-}
999 #endif
1000
1001 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1002 --
1003 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1004 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1005 -- > fromListWithKey f [] == empty
1006
1007 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1008 fromListWithKey f xs
1009 = foldlStrict ins empty xs
1010 where
1011 ins t (k,x) = insertWithKey f k x t
1012 #if __GLASGOW_HASKELL__ >= 700
1013 {-# INLINABLE fromListWithKey #-}
1014 #endif
1015
1016 {--------------------------------------------------------------------
1017 Building trees from ascending/descending lists can be done in linear time.
1018
1019 Note that if [xs] is ascending that:
1020 fromAscList xs == fromList xs
1021 fromAscListWith f xs == fromListWith f xs
1022 --------------------------------------------------------------------}
1023 -- | /O(n)/. Build a map from an ascending list in linear time.
1024 -- /The precondition (input list is ascending) is not checked./
1025 --
1026 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1027 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1028 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1029 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1030
1031 fromAscList :: Eq k => [(k,a)] -> Map k a
1032 fromAscList xs
1033 = fromAscListWithKey (\_ x _ -> x) xs
1034 #if __GLASGOW_HASKELL__ >= 700
1035 {-# INLINABLE fromAscList #-}
1036 #endif
1037
1038 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1039 -- /The precondition (input list is ascending) is not checked./
1040 --
1041 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1042 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1043 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1044
1045 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1046 fromAscListWith f xs
1047 = fromAscListWithKey (\_ x y -> f x y) xs
1048 #if __GLASGOW_HASKELL__ >= 700
1049 {-# INLINABLE fromAscListWith #-}
1050 #endif
1051
1052 -- | /O(n)/. Build a map from an ascending list in linear time with a
1053 -- combining function for equal keys.
1054 -- /The precondition (input list is ascending) is not checked./
1055 --
1056 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1057 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1058 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1059 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1060
1061 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1062 fromAscListWithKey f xs
1063 = fromDistinctAscList (combineEq f xs)
1064 where
1065 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1066 combineEq _ xs'
1067 = case xs' of
1068 [] -> []
1069 [x] -> [x]
1070 (x:xx) -> combineEq' x xx
1071
1072 combineEq' z [] = [z]
1073 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1074 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1075 | otherwise = z:combineEq' x xs'
1076 #if __GLASGOW_HASKELL__ >= 700
1077 {-# INLINABLE fromAscListWithKey #-}
1078 #endif
1079
1080 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1081 -- /The precondition is not checked./
1082 --
1083 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1084 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1085 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1086
1087 fromDistinctAscList :: [(k,a)] -> Map k a
1088 fromDistinctAscList xs
1089 = create const (length xs) xs
1090 where
1091 -- 1) use continuations so that we use heap space instead of stack space.
1092 -- 2) special case for n==5 to create bushier trees.
1093 create c 0 xs' = c Tip xs'
1094 create c 5 xs' = case xs' of
1095 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1096 -> x1 `seq` x2 `seq` x3 `seq` x4 `seq` x5 `seq`
1097 c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3))
1098 (singleton k5 x5)) xx
1099 _ -> error "fromDistinctAscList create"
1100 create c n xs' = seq nr $ create (createR nr c) nl xs'
1101 where nl = n `div` 2
1102 nr = n - nl - 1
1103
1104 createR n c l ((k,x):ys) = x `seq` create (createB l k x c) n ys
1105 createR _ _ _ [] = error "fromDistinctAscList createR []"
1106 createB l k x c r zs = x `seq` c (bin k x l r) zs