Merge pull request #24 from ekmett/master
[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 -- See the notes at the beginning of Data.Map.Base.
53
54 module Data.Map.Strict
55 (
56 -- * Strictness properties
57 -- $strictness
58
59 -- * Map type
60 #if !defined(TESTING)
61 Map -- instance Eq,Show,Read
62 #else
63 Map(..) -- instance Eq,Show,Read
64 #endif
65
66 -- * Operators
67 , (!), (\\)
68
69 -- * Query
70 , null
71 , size
72 , member
73 , notMember
74 , lookup
75 , findWithDefault
76 , lookupLT
77 , lookupGT
78 , lookupLE
79 , lookupGE
80
81 -- * Construction
82 , empty
83 , singleton
84
85 -- ** Insertion
86 , insert
87 , insertWith
88 , insertWithKey
89 , insertLookupWithKey
90
91 -- ** Delete\/Update
92 , delete
93 , adjust
94 , adjustWithKey
95 , update
96 , updateWithKey
97 , updateLookupWithKey
98 , alter
99
100 -- * Combine
101
102 -- ** Union
103 , union
104 , unionWith
105 , unionWithKey
106 , unions
107 , unionsWith
108
109 -- ** Difference
110 , difference
111 , differenceWith
112 , differenceWithKey
113
114 -- ** Intersection
115 , intersection
116 , intersectionWith
117 , intersectionWithKey
118
119 -- ** Universal combining function
120 , mergeWithKey
121
122 -- * Traversal
123 -- ** Map
124 , map
125 , mapWithKey
126 , traverseWithKey
127 , mapAccum
128 , mapAccumWithKey
129 , mapAccumRWithKey
130 , mapKeys
131 , mapKeysWith
132 , mapKeysMonotonic
133
134 -- * Folds
135 , foldr
136 , foldl
137 , foldrWithKey
138 , foldlWithKey
139 , foldMapWithKey
140
141 -- ** Strict folds
142 , foldr'
143 , foldl'
144 , foldrWithKey'
145 , foldlWithKey'
146
147 -- * Conversion
148 , elems
149 , keys
150 , assocs
151 , keysSet
152 , fromSet
153
154 -- ** Lists
155 , toList
156 , fromList
157 , fromListWith
158 , fromListWithKey
159
160 -- ** Ordered lists
161 , toAscList
162 , toDescList
163 , fromAscList
164 , fromAscListWith
165 , fromAscListWithKey
166 , fromDistinctAscList
167
168 -- * Filter
169 , filter
170 , filterWithKey
171 , partition
172 , partitionWithKey
173
174 , mapMaybe
175 , mapMaybeWithKey
176 , mapEither
177 , mapEitherWithKey
178
179 , split
180 , splitLookup
181
182 -- * Submap
183 , isSubmapOf, isSubmapOfBy
184 , isProperSubmapOf, isProperSubmapOfBy
185
186 -- * Indexed
187 , lookupIndex
188 , findIndex
189 , elemAt
190 , updateAt
191 , deleteAt
192
193 -- * Min\/Max
194 , findMin
195 , findMax
196 , deleteMin
197 , deleteMax
198 , deleteFindMin
199 , deleteFindMax
200 , updateMin
201 , updateMax
202 , updateMinWithKey
203 , updateMaxWithKey
204 , minView
205 , maxView
206 , minViewWithKey
207 , maxViewWithKey
208
209 -- * Debugging
210 , showTree
211 , showTreeWith
212 , valid
213
214 #if defined(TESTING)
215 -- * Internals
216 , bin
217 , balanced
218 , join
219 , merge
220 #endif
221 ) where
222
223 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
224
225 import Data.Map.Base hiding
226 ( findWithDefault
227 , singleton
228 , insert
229 , insertWith
230 , insertWithKey
231 , insertLookupWithKey
232 , adjust
233 , adjustWithKey
234 , update
235 , updateWithKey
236 , updateLookupWithKey
237 , alter
238 , unionWith
239 , unionWithKey
240 , unionsWith
241 , differenceWith
242 , differenceWithKey
243 , intersectionWith
244 , intersectionWithKey
245 , mergeWithKey
246 , map
247 , mapWithKey
248 , mapAccum
249 , mapAccumWithKey
250 , mapAccumRWithKey
251 , mapKeysWith
252 , fromSet
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 qualified Data.Set.Base as Set
271 import Data.StrictPair
272 import Data.Bits (shiftL, shiftR)
273
274 -- Use macros to define strictness of functions. STRICT_x_OF_y
275 -- denotes an y-ary function strict in the x-th parameter. Similarly
276 -- STRICT_x_y_OF_z denotes an z-ary function strict in the x-th and
277 -- y-th parameter. We do not use BangPatterns, because they are not
278 -- in any standard and we want the compilers to be compiled by as many
279 -- compilers as possible.
280 #define STRICT_1_OF_2(fn) fn arg _ | arg `seq` False = undefined
281 #define STRICT_1_OF_3(fn) fn arg _ _ | arg `seq` False = undefined
282 #define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
283 #define STRICT_1_2_OF_3(fn) fn arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
284 #define STRICT_2_3_OF_4(fn) fn _ arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
285
286 -- $strictness
287 --
288 -- This module satisfies the following strictness properties:
289 --
290 -- 1. Key and value arguments are evaluated to WHNF;
291 --
292 -- 2. Keys and values are evaluated to WHNF before they are stored in
293 -- the map.
294 --
295 -- Here are some examples that illustrate the first property:
296 --
297 -- > insertWith (\ new old -> old) k undefined m == undefined
298 -- > delete undefined m == undefined
299 --
300 -- Here are some examples that illustrate the second property:
301 --
302 -- > map (\ v -> undefined) m == undefined -- m is not empty
303 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
304
305 {--------------------------------------------------------------------
306 Query
307 --------------------------------------------------------------------}
308
309 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
310 -- the value at key @k@ or returns default value @def@
311 -- when the key is not in the map.
312 --
313 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
314 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
315
316 -- See Map.Base.Note: Local 'go' functions and capturing
317 findWithDefault :: Ord k => a -> k -> Map k a -> a
318 findWithDefault def k = def `seq` k `seq` go
319 where
320 go Tip = def
321 go (Bin _ kx x l r) = case compare k kx of
322 LT -> go l
323 GT -> go r
324 EQ -> x
325 #if __GLASGOW_HASKELL__ >= 700
326 {-# INLINABLE findWithDefault #-}
327 #else
328 {-# INLINE findWithDefault #-}
329 #endif
330
331 {--------------------------------------------------------------------
332 Construction
333 --------------------------------------------------------------------}
334
335 -- | /O(1)/. A map with a single element.
336 --
337 -- > singleton 1 'a' == fromList [(1, 'a')]
338 -- > size (singleton 1 'a') == 1
339
340 singleton :: k -> a -> Map k a
341 singleton k x = x `seq` Bin 1 k x Tip Tip
342 {-# INLINE singleton #-}
343
344 {--------------------------------------------------------------------
345 Insertion
346 --------------------------------------------------------------------}
347 -- | /O(log n)/. Insert a new key and value in the map.
348 -- If the key is already present in the map, the associated value is
349 -- replaced with the supplied value. 'insert' is equivalent to
350 -- @'insertWith' 'const'@.
351 --
352 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
353 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
354 -- > insert 5 'x' empty == singleton 5 'x'
355
356 -- See Map.Base.Note: Type of local 'go' function
357 insert :: Ord k => k -> a -> Map k a -> Map k a
358 insert = go
359 where
360 go :: Ord k => k -> a -> Map k a -> Map k a
361 STRICT_1_2_OF_3(go)
362 go kx x Tip = singleton kx x
363 go kx x (Bin sz ky y l r) =
364 case compare kx ky of
365 LT -> balanceL ky y (go kx x l) r
366 GT -> balanceR ky y l (go kx x r)
367 EQ -> Bin sz kx x l r
368 #if __GLASGOW_HASKELL__ >= 700
369 {-# INLINABLE insert #-}
370 #else
371 {-# INLINE insert #-}
372 #endif
373
374 -- | /O(log n)/. Insert with a function, combining new value and old value.
375 -- @'insertWith' f key value mp@
376 -- will insert the pair (key, value) into @mp@ if key does
377 -- not exist in the map. If the key does exist, the function will
378 -- insert the pair @(key, f new_value old_value)@.
379 --
380 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
381 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
382 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
383
384 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
385 insertWith f = insertWithKey (\_ x' y' -> f x' y')
386 #if __GLASGOW_HASKELL__ >= 700
387 {-# INLINABLE insertWith #-}
388 #else
389 {-# INLINE insertWith #-}
390 #endif
391
392 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
393 -- @'insertWithKey' f key value mp@
394 -- will insert the pair (key, value) into @mp@ if key does
395 -- not exist in the map. If the key does exist, the function will
396 -- insert the pair @(key,f key new_value old_value)@.
397 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
398 --
399 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
400 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
401 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
402 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
403
404 -- See Map.Base.Note: Type of local 'go' function
405 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
406 insertWithKey = go
407 where
408 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
409 STRICT_2_3_OF_4(go)
410 go _ kx x Tip = singleton kx x
411 go f kx x (Bin sy ky y l r) =
412 case compare kx ky of
413 LT -> balanceL ky y (go f kx x l) r
414 GT -> balanceR ky y l (go f kx x r)
415 EQ -> let x' = f kx x y
416 in x' `seq` Bin sy kx x' l r
417 #if __GLASGOW_HASKELL__ >= 700
418 {-# INLINABLE insertWithKey #-}
419 #else
420 {-# INLINE insertWithKey #-}
421 #endif
422
423 -- | /O(log n)/. Combines insert operation with old value retrieval.
424 -- The expression (@'insertLookupWithKey' f k x map@)
425 -- is a pair where the first element is equal to (@'lookup' k map@)
426 -- and the second element equal to (@'insertWithKey' f k x map@).
427 --
428 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
429 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
430 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
431 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
432 --
433 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
434 --
435 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
436 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
437 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
438
439 -- See Map.Base.Note: Type of local 'go' function
440 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
441 -> (Maybe a, Map k a)
442 insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0
443 where
444 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a)
445 STRICT_2_3_OF_4(go)
446 go _ kx x Tip = Nothing :*: singleton kx x
447 go f kx x (Bin sy ky y l r) =
448 case compare kx ky of
449 LT -> let (found :*: l') = go f kx x l
450 in found :*: balanceL ky y l' r
451 GT -> let (found :*: r') = go f kx x r
452 in found :*: balanceR ky y l r'
453 EQ -> let x' = f kx x y
454 in x' `seq` (Just y :*: Bin sy kx x' l r)
455 #if __GLASGOW_HASKELL__ >= 700
456 {-# INLINABLE insertLookupWithKey #-}
457 #else
458 {-# INLINE insertLookupWithKey #-}
459 #endif
460
461 {--------------------------------------------------------------------
462 Deletion
463 --------------------------------------------------------------------}
464
465 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
466 -- When the key is not
467 -- a member of the map, the original map is returned.
468 --
469 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
470 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
471 -- > adjust ("new " ++) 7 empty == empty
472
473 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
474 adjust f = adjustWithKey (\_ x -> f x)
475 #if __GLASGOW_HASKELL__ >= 700
476 {-# INLINABLE adjust #-}
477 #else
478 {-# INLINE adjust #-}
479 #endif
480
481 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
482 -- a member of the map, the original map is returned.
483 --
484 -- > let f key x = (show key) ++ ":new " ++ x
485 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
486 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
487 -- > adjustWithKey f 7 empty == empty
488
489 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
490 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
491 #if __GLASGOW_HASKELL__ >= 700
492 {-# INLINABLE adjustWithKey #-}
493 #else
494 {-# INLINE adjustWithKey #-}
495 #endif
496
497 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
498 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
499 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
500 --
501 -- > let f x = if x == "a" then Just "new a" else Nothing
502 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
503 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
504 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
505
506 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
507 update f = updateWithKey (\_ x -> f x)
508 #if __GLASGOW_HASKELL__ >= 700
509 {-# INLINABLE update #-}
510 #else
511 {-# INLINE update #-}
512 #endif
513
514 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
515 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
516 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
517 -- to the new value @y@.
518 --
519 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
520 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
521 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
522 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
523
524 -- See Map.Base.Note: Type of local 'go' function
525 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
526 updateWithKey = go
527 where
528 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
529 STRICT_2_OF_3(go)
530 go _ _ Tip = Tip
531 go f k(Bin sx kx x l r) =
532 case compare k kx of
533 LT -> balanceR kx x (go f k l) r
534 GT -> balanceL kx x l (go f k r)
535 EQ -> case f kx x of
536 Just x' -> x' `seq` Bin sx kx x' l r
537 Nothing -> glue l r
538 #if __GLASGOW_HASKELL__ >= 700
539 {-# INLINABLE updateWithKey #-}
540 #else
541 {-# INLINE updateWithKey #-}
542 #endif
543
544 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
545 -- The function returns changed value, if it is updated.
546 -- Returns the original key value if the map entry is deleted.
547 --
548 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
549 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
550 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
551 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
552
553 -- See Map.Base.Note: Type of local 'go' function
554 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
555 updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0
556 where
557 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
558 STRICT_2_OF_3(go)
559 go _ _ Tip = (Nothing :*: Tip)
560 go f k (Bin sx kx x l r) =
561 case compare k kx of
562 LT -> let (found :*: l') = go f k l
563 in found :*: balanceR kx x l' r
564 GT -> let (found :*: r') = go f k r
565 in found :*: balanceL kx x l r'
566 EQ -> case f kx x of
567 Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
568 Nothing -> (Just x :*: glue l r)
569 #if __GLASGOW_HASKELL__ >= 700
570 {-# INLINABLE updateLookupWithKey #-}
571 #else
572 {-# INLINE updateLookupWithKey #-}
573 #endif
574
575 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
576 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
577 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
578 --
579 -- > let f _ = Nothing
580 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
581 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
582 -- >
583 -- > let f _ = Just "c"
584 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
585 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
586
587 -- See Map.Base.Note: Type of local 'go' function
588 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
589 alter = go
590 where
591 go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
592 STRICT_2_OF_3(go)
593 go f k Tip = case f Nothing of
594 Nothing -> Tip
595 Just x -> singleton k x
596
597 go f k (Bin sx kx x l r) = case compare k kx of
598 LT -> balance kx x (go f k l) r
599 GT -> balance kx x l (go f k r)
600 EQ -> case f (Just x) of
601 Just x' -> x' `seq` Bin sx kx x' l r
602 Nothing -> glue l r
603 #if __GLASGOW_HASKELL__ >= 700
604 {-# INLINABLE alter #-}
605 #else
606 {-# INLINE alter #-}
607 #endif
608
609 {--------------------------------------------------------------------
610 Indexing
611 --------------------------------------------------------------------}
612
613 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
614 -- invalid index is used.
615 --
616 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
617 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
618 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
619 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
620 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
621 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
622 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
623 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
624
625 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
626 updateAt f i t = i `seq`
627 case t of
628 Tip -> error "Map.updateAt: index out of range"
629 Bin sx kx x l r -> case compare i sizeL of
630 LT -> balanceR kx x (updateAt f i l) r
631 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
632 EQ -> case f kx x of
633 Just x' -> x' `seq` Bin sx kx x' l r
634 Nothing -> glue l r
635 where
636 sizeL = size l
637
638 {--------------------------------------------------------------------
639 Minimal, Maximal
640 --------------------------------------------------------------------}
641
642 -- | /O(log n)/. Update the value at the minimal key.
643 --
644 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
645 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
646
647 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
648 updateMin f m
649 = updateMinWithKey (\_ x -> f x) m
650
651 -- | /O(log n)/. Update the value at the maximal key.
652 --
653 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
654 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
655
656 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
657 updateMax f m
658 = updateMaxWithKey (\_ x -> f x) m
659
660
661 -- | /O(log n)/. Update the value at the minimal key.
662 --
663 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
664 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
665
666 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
667 updateMinWithKey _ Tip = Tip
668 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
669 Nothing -> r
670 Just x' -> x' `seq` Bin sx kx x' Tip r
671 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
672
673 -- | /O(log n)/. Update the value at the maximal key.
674 --
675 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
676 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
677
678 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
679 updateMaxWithKey _ Tip = Tip
680 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
681 Nothing -> l
682 Just x' -> x' `seq` Bin sx kx x' l Tip
683 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
684
685 {--------------------------------------------------------------------
686 Union.
687 --------------------------------------------------------------------}
688
689 -- | The union of a list of maps, with a combining operation:
690 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
691 --
692 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
693 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
694
695 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
696 unionsWith f ts
697 = foldlStrict (unionWith f) empty ts
698 #if __GLASGOW_HASKELL__ >= 700
699 {-# INLINABLE unionsWith #-}
700 #endif
701
702 {--------------------------------------------------------------------
703 Union with a combining function
704 --------------------------------------------------------------------}
705 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
706 --
707 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
708
709 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
710 unionWith f m1 m2
711 = unionWithKey (\_ x y -> f x y) m1 m2
712 #if __GLASGOW_HASKELL__ >= 700
713 {-# INLINABLE unionWith #-}
714 #endif
715
716 -- | /O(n+m)/.
717 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
718 --
719 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
720 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
721
722 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
723 unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
724 #if __GLASGOW_HASKELL__ >= 700
725 {-# INLINABLE unionWithKey #-}
726 #endif
727
728 {--------------------------------------------------------------------
729 Difference
730 --------------------------------------------------------------------}
731
732 -- | /O(n+m)/. Difference with a combining function.
733 -- When two equal keys are
734 -- encountered, the combining function is applied to the values of these keys.
735 -- If it returns 'Nothing', the element is discarded (proper set difference). If
736 -- it returns (@'Just' y@), the element is updated with a new value @y@.
737 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
738 --
739 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
740 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
741 -- > == singleton 3 "b:B"
742
743 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
744 differenceWith f m1 m2
745 = differenceWithKey (\_ x y -> f x y) m1 m2
746 #if __GLASGOW_HASKELL__ >= 700
747 {-# INLINABLE differenceWith #-}
748 #endif
749
750 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
751 -- encountered, the combining function is applied to the key and both values.
752 -- If it returns 'Nothing', the element is discarded (proper set difference). If
753 -- it returns (@'Just' y@), the element is updated with a new value @y@.
754 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
755 --
756 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
757 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
758 -- > == singleton 3 "3:b|B"
759
760 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
761 differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
762 #if __GLASGOW_HASKELL__ >= 700
763 {-# INLINABLE differenceWithKey #-}
764 #endif
765
766
767 {--------------------------------------------------------------------
768 Intersection
769 --------------------------------------------------------------------}
770
771 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
772 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
773 --
774 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
775
776 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
777 intersectionWith f m1 m2
778 = intersectionWithKey (\_ x y -> f x y) m1 m2
779 #if __GLASGOW_HASKELL__ >= 700
780 {-# INLINABLE intersectionWith #-}
781 #endif
782
783 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
784 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
785 --
786 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
787 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
788
789
790 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
791 intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
792 #if __GLASGOW_HASKELL__ >= 700
793 {-# INLINABLE intersectionWithKey #-}
794 #endif
795
796
797 {--------------------------------------------------------------------
798 MergeWithKey
799 --------------------------------------------------------------------}
800
801 -- | /O(n+m)/. A high-performance universal combining function. This function
802 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
803 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
804 -- used to define other custom combine functions.
805 --
806 -- Please make sure you know what is going on when using 'mergeWithKey',
807 -- otherwise you can be surprised by unexpected code growth or even
808 -- corruption of the data structure.
809 --
810 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
811 -- site. You should therefore use 'mergeWithKey' only to define your custom
812 -- combining functions. For example, you could define 'unionWithKey',
813 -- 'differenceWithKey' and 'intersectionWithKey' as
814 --
815 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
816 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
817 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
818 --
819 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
820 -- 'IntMap's is created, such that
821 --
822 -- * if a key is present in both maps, it is passed with both corresponding
823 -- values to the @combine@ function. Depending on the result, the key is either
824 -- present in the result with specified value, or is left out;
825 --
826 -- * a nonempty subtree present only in the first map is passed to @only1@ and
827 -- the output is added to the result;
828 --
829 -- * a nonempty subtree present only in the second map is passed to @only2@ and
830 -- the output is added to the result.
831 --
832 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
833 -- The values can be modified arbitrarily. Most common variants of @only1@ and
834 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
835 -- @'filterWithKey' f@ could be used for any @f@.
836
837 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
838 -> Map k a -> Map k b -> Map k c
839 mergeWithKey f g1 g2 = go
840 where
841 go Tip t2 = g2 t2
842 go t1 Tip = g1 t1
843 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
844
845 hedgeMerge _ _ t1 Tip = g1 t1
846 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ join kx x (filterGt blo l) (filterLt bhi r)
847 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
848 (found, trim_t2) = trimLookupLo kx bhi t2
849 r' = hedgeMerge bmi bhi r trim_t2
850 in case found of
851 Nothing -> case g1 (singleton kx x) of
852 Tip -> merge l' r'
853 (Bin _ _ x' Tip Tip) -> join kx x' l' r'
854 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
855 Just x2 -> case f kx x x2 of
856 Nothing -> merge l' r'
857 Just x' -> x' `seq` join kx x' l' r'
858 where bmi = JustS kx
859 {-# INLINE mergeWithKey #-}
860
861 {--------------------------------------------------------------------
862 Filter and partition
863 --------------------------------------------------------------------}
864
865 -- | /O(n)/. Map values and collect the 'Just' results.
866 --
867 -- > let f x = if x == "a" then Just "new a" else Nothing
868 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
869
870 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
871 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
872
873 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
874 --
875 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
876 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
877
878 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
879 mapMaybeWithKey _ Tip = Tip
880 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
881 Just y -> y `seq` join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
882 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
883
884 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
885 --
886 -- > let f a = if a < "c" then Left a else Right a
887 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
888 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
889 -- >
890 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
891 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
892
893 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
894 mapEither f m
895 = mapEitherWithKey (\_ x -> f x) m
896
897 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
898 --
899 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
900 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
901 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
902 -- >
903 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
904 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
905
906 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
907 mapEitherWithKey f0 t0 = toPair $ go f0 t0
908 where
909 go _ Tip = (Tip :*: Tip)
910 go f (Bin _ kx x l r) = case f kx x of
911 Left y -> y `seq` (join kx y l1 r1 :*: merge l2 r2)
912 Right z -> z `seq` (merge l1 r1 :*: join kx z l2 r2)
913 where
914 (l1 :*: l2) = go f l
915 (r1 :*: r2) = go f r
916
917 {--------------------------------------------------------------------
918 Mapping
919 --------------------------------------------------------------------}
920 -- | /O(n)/. Map a function over all values in the map.
921 --
922 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
923
924 map :: (a -> b) -> Map k a -> Map k b
925 map _ Tip = Tip
926 map f (Bin sx kx x l r) = let x' = f x in x' `seq` Bin sx kx x' (map f l) (map f r)
927
928 -- | /O(n)/. Map a function over all values in the map.
929 --
930 -- > let f key x = (show key) ++ ":" ++ x
931 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
932
933 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
934 mapWithKey _ Tip = Tip
935 mapWithKey f (Bin sx kx x l r) = let x' = f kx x
936 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
937
938 -- | /O(n)/. The function 'mapAccum' threads an accumulating
939 -- argument through the map in ascending order of keys.
940 --
941 -- > let f a b = (a ++ b, b ++ "X")
942 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
943
944 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
945 mapAccum f a m
946 = mapAccumWithKey (\a' _ x' -> f a' x') a m
947
948 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
949 -- argument through the map in ascending order of keys.
950 --
951 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
952 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
953
954 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
955 mapAccumWithKey f a t
956 = mapAccumL f a t
957
958 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
959 -- argument through the map in ascending order of keys.
960 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
961 mapAccumL _ a Tip = (a,Tip)
962 mapAccumL f a (Bin sx kx x l r) =
963 let (a1,l') = mapAccumL f a l
964 (a2,x') = f a1 kx x
965 (a3,r') = mapAccumL f a2 r
966 in x' `seq` (a3,Bin sx kx x' l' r')
967
968 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
969 -- argument through the map in descending order of keys.
970 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
971 mapAccumRWithKey _ a Tip = (a,Tip)
972 mapAccumRWithKey f a (Bin sx kx x l r) =
973 let (a1,r') = mapAccumRWithKey f a r
974 (a2,x') = f a1 kx x
975 (a3,l') = mapAccumRWithKey f a2 l
976 in x' `seq` (a3,Bin sx kx x' l' r')
977
978 -- | /O(n*log n)/.
979 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
980 --
981 -- The size of the result may be smaller if @f@ maps two or more distinct
982 -- keys to the same new key. In this case the associated values will be
983 -- combined using @c@.
984 --
985 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
986 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
987
988 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
989 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
990 #if __GLASGOW_HASKELL__ >= 700
991 {-# INLINABLE mapKeysWith #-}
992 #endif
993
994 {--------------------------------------------------------------------
995 Conversions
996 --------------------------------------------------------------------}
997
998 -- | /O(n)/. Build a map from a set of keys and a function which for each key
999 -- computes its value.
1000 --
1001 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1002 -- > fromSet undefined Data.Set.empty == empty
1003
1004 fromSet :: (k -> a) -> Set.Set k -> Map k a
1005 fromSet _ Set.Tip = Tip
1006 fromSet f (Set.Bin sz x l r) = case f x of v -> v `seq` Bin sz x v (fromSet f l) (fromSet f r)
1007
1008 {--------------------------------------------------------------------
1009 Lists
1010 use [foldlStrict] to reduce demand on the control-stack
1011 --------------------------------------------------------------------}
1012 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1013 -- If the list contains more than one value for the same key, the last value
1014 -- for the key is retained.
1015 --
1016 -- If the keys of the list are ordered, linear-time implementation is used,
1017 -- with the performance equal to 'fromDistinctAscList'.
1018 --
1019 -- > fromList [] == empty
1020 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1021 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1022
1023 -- For some reason, when 'singleton' is used in fromList or in
1024 -- create, it is not inlined, so we inline it manually.
1025 fromList :: Ord k => [(k,a)] -> Map k a
1026 fromList [] = Tip
1027 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1028 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1029 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1030 where
1031 not_ordered _ [] = False
1032 not_ordered kx ((ky,_) : _) = kx >= ky
1033 {-# INLINE not_ordered #-}
1034
1035 fromList' t0 xs = foldlStrict ins t0 xs
1036 where ins t (k,x) = insert k x t
1037
1038 STRICT_1_OF_3(go)
1039 go _ t [] = t
1040 go _ t [(kx, x)] = x `seq` insertMax kx x t
1041 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1042 | otherwise = case create s xss of
1043 (r, ys, []) -> x `seq` go (s `shiftL` 1) (join kx x l r) ys
1044 (r, _, ys) -> x `seq` fromList' (join kx x l r) ys
1045
1046 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1047 -- represent not yet processed elements and only one of them can be nonempty.
1048 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1049 -- and must be inserted using fromList'. Otherwise the keys have been
1050 -- ordered so far.
1051 STRICT_1_OF_2(create)
1052 create _ [] = (Tip, [], [])
1053 create s xs@(xp : xss)
1054 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1055 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1056 | otherwise = case create (s `shiftR` 1) xs of
1057 res@(_, [], _) -> res
1058 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1059 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1060 | otherwise -> case create (s `shiftR` 1) yss of
1061 (r, zs, ws) -> y `seq` (join ky y l r, zs, ws)
1062 #if __GLASGOW_HASKELL__ >= 700
1063 {-# INLINABLE fromList #-}
1064 #endif
1065
1066 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1067 --
1068 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1069 -- > fromListWith (++) [] == empty
1070
1071 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1072 fromListWith f xs
1073 = fromListWithKey (\_ x y -> f x y) xs
1074 #if __GLASGOW_HASKELL__ >= 700
1075 {-# INLINABLE fromListWith #-}
1076 #endif
1077
1078 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1079 --
1080 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1081 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1082 -- > fromListWithKey f [] == empty
1083
1084 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1085 fromListWithKey f xs
1086 = foldlStrict ins empty xs
1087 where
1088 ins t (k,x) = insertWithKey f k x t
1089 #if __GLASGOW_HASKELL__ >= 700
1090 {-# INLINABLE fromListWithKey #-}
1091 #endif
1092
1093 {--------------------------------------------------------------------
1094 Building trees from ascending/descending lists can be done in linear time.
1095
1096 Note that if [xs] is ascending that:
1097 fromAscList xs == fromList xs
1098 fromAscListWith f xs == fromListWith f xs
1099 --------------------------------------------------------------------}
1100 -- | /O(n)/. Build a map from an ascending list in linear time.
1101 -- /The precondition (input list is ascending) is not checked./
1102 --
1103 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1104 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1105 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1106 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1107
1108 fromAscList :: Eq k => [(k,a)] -> Map k a
1109 fromAscList xs
1110 = fromAscListWithKey (\_ x _ -> x) xs
1111 #if __GLASGOW_HASKELL__ >= 700
1112 {-# INLINABLE fromAscList #-}
1113 #endif
1114
1115 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1116 -- /The precondition (input list is ascending) is not checked./
1117 --
1118 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1119 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1120 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1121
1122 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1123 fromAscListWith f xs
1124 = fromAscListWithKey (\_ x y -> f x y) xs
1125 #if __GLASGOW_HASKELL__ >= 700
1126 {-# INLINABLE fromAscListWith #-}
1127 #endif
1128
1129 -- | /O(n)/. Build a map from an ascending list in linear time with a
1130 -- combining function for equal keys.
1131 -- /The precondition (input list is ascending) is not checked./
1132 --
1133 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1134 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1135 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1136 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1137
1138 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1139 fromAscListWithKey f xs
1140 = fromDistinctAscList (combineEq f xs)
1141 where
1142 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1143 combineEq _ xs'
1144 = case xs' of
1145 [] -> []
1146 [x] -> [x]
1147 (x:xx) -> combineEq' x xx
1148
1149 combineEq' z [] = [z]
1150 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1151 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1152 | otherwise = z:combineEq' x xs'
1153 #if __GLASGOW_HASKELL__ >= 700
1154 {-# INLINABLE fromAscListWithKey #-}
1155 #endif
1156
1157 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1158 -- /The precondition is not checked./
1159 --
1160 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1161 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1162 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1163
1164 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1165 -- create, it is not inlined, so we inline it manually.
1166 fromDistinctAscList :: [(k,a)] -> Map k a
1167 fromDistinctAscList [] = Tip
1168 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1169 where
1170 STRICT_1_OF_3(go)
1171 go _ t [] = t
1172 go s l ((kx, x) : xs) = case create s xs of
1173 (r, ys) -> x `seq` go (s `shiftL` 1) (join kx x l r) ys
1174
1175 STRICT_1_OF_2(create)
1176 create _ [] = (Tip, [])
1177 create s xs@(x' : xs')
1178 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1179 | otherwise = case create (s `shiftR` 1) xs of
1180 res@(_, []) -> res
1181 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1182 (r, zs) -> y `seq` (join ky y l r, zs)