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