Remove all support for nhc98 and GHC <7
[packages/containers.git] / Data / Map / Strict.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE BangPatterns #-}
3 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
4 {-# LANGUAGE Trustworthy #-}
5 #endif
6
7 #include "containers.h"
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : Data.Map.Strict
12 -- Copyright : (c) Daan Leijen 2002
13 -- (c) Andriy Palamarchuk 2008
14 -- License : BSD-style
15 -- Maintainer : libraries@haskell.org
16 -- Stability : provisional
17 -- Portability : portable
18 --
19 -- An efficient implementation of ordered maps from keys to values
20 -- (dictionaries).
21 --
22 -- API of this module is strict in both the keys and the values.
23 -- If you need value-lazy maps, use "Data.Map.Lazy" instead.
24 -- The 'Map' type is shared between the lazy and strict modules,
25 -- meaning that the same 'Map' value can be passed to functions in
26 -- both modules (although that is rarely needed).
27 --
28 -- These modules are intended to be imported qualified, to avoid name
29 -- clashes with Prelude functions, e.g.
30 --
31 -- > import qualified Data.Map.Strict as Map
32 --
33 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
34 -- trees of /bounded balance/) as described by:
35 --
36 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
37 -- Journal of Functional Programming 3(4):553-562, October 1993,
38 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
39 --
40 -- * J. Nievergelt and E.M. Reingold,
41 -- \"/Binary search trees of bounded balance/\",
42 -- SIAM journal of computing 2(1), March 1973.
43 --
44 -- Note that the implementation is /left-biased/ -- the elements of a
45 -- first argument are always preferred to the second, for example in
46 -- 'union' or 'insert'.
47 --
48 -- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of
49 -- this condition is not detected and if the size limit is exceeded, its
50 -- behaviour is undefined.
51 --
52 -- Operation comments contain the operation time complexity in
53 -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
54 --
55 -- Be aware that the 'Functor', 'Traversable' and 'Data' instances
56 -- are the same as for the "Data.Map.Lazy" module, so if they are used
57 -- on strict maps, the resulting maps will be lazy.
58 -----------------------------------------------------------------------------
59
60 -- See the notes at the beginning of Data.Map.Base.
61
62 module Data.Map.Strict
63 (
64 -- * Strictness properties
65 -- $strictness
66
67 -- * Map type
68 #if !defined(TESTING)
69 Map -- instance Eq,Show,Read
70 #else
71 Map(..) -- instance Eq,Show,Read
72 #endif
73
74 -- * Operators
75 , (!), (\\)
76
77 -- * Query
78 , null
79 , size
80 , member
81 , notMember
82 , lookup
83 , findWithDefault
84 , lookupLT
85 , lookupGT
86 , lookupLE
87 , lookupGE
88
89 -- * Construction
90 , empty
91 , singleton
92
93 -- ** Insertion
94 , insert
95 , insertWith
96 , insertWithKey
97 , insertLookupWithKey
98
99 -- ** Delete\/Update
100 , delete
101 , adjust
102 , adjustWithKey
103 , update
104 , updateWithKey
105 , updateLookupWithKey
106 , alter
107
108 -- * Combine
109
110 -- ** Union
111 , union
112 , unionWith
113 , unionWithKey
114 , unions
115 , unionsWith
116
117 -- ** Difference
118 , difference
119 , differenceWith
120 , differenceWithKey
121
122 -- ** Intersection
123 , intersection
124 , intersectionWith
125 , intersectionWithKey
126
127 -- ** Universal combining function
128 , mergeWithKey
129
130 -- * Traversal
131 -- ** Map
132 , map
133 , mapWithKey
134 , traverseWithKey
135 , mapAccum
136 , mapAccumWithKey
137 , mapAccumRWithKey
138 , mapKeys
139 , mapKeysWith
140 , mapKeysMonotonic
141
142 -- * Folds
143 , foldr
144 , foldl
145 , foldrWithKey
146 , foldlWithKey
147 , foldMapWithKey
148
149 -- ** Strict folds
150 , foldr'
151 , foldl'
152 , foldrWithKey'
153 , foldlWithKey'
154
155 -- * Conversion
156 , elems
157 , keys
158 , assocs
159 , keysSet
160 , fromSet
161
162 -- ** Lists
163 , toList
164 , fromList
165 , fromListWith
166 , fromListWithKey
167
168 -- ** Ordered lists
169 , toAscList
170 , toDescList
171 , fromAscList
172 , fromAscListWith
173 , fromAscListWithKey
174 , fromDistinctAscList
175
176 -- * Filter
177 , filter
178 , filterWithKey
179 , partition
180 , partitionWithKey
181
182 , mapMaybe
183 , mapMaybeWithKey
184 , mapEither
185 , mapEitherWithKey
186
187 , split
188 , splitLookup
189 , splitRoot
190
191 -- * Submap
192 , isSubmapOf, isSubmapOfBy
193 , isProperSubmapOf, isProperSubmapOfBy
194
195 -- * Indexed
196 , lookupIndex
197 , findIndex
198 , elemAt
199 , updateAt
200 , deleteAt
201
202 -- * Min\/Max
203 , findMin
204 , findMax
205 , deleteMin
206 , deleteMax
207 , deleteFindMin
208 , deleteFindMax
209 , updateMin
210 , updateMax
211 , updateMinWithKey
212 , updateMaxWithKey
213 , minView
214 , maxView
215 , minViewWithKey
216 , maxViewWithKey
217
218 -- * Debugging
219 , showTree
220 , showTreeWith
221 , valid
222
223 #if defined(TESTING)
224 -- * Internals
225 , bin
226 , balanced
227 , link
228 , merge
229 #endif
230 ) where
231
232 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
233
234 import Data.Map.Base hiding
235 ( findWithDefault
236 , singleton
237 , insert
238 , insertWith
239 , insertWithKey
240 , insertLookupWithKey
241 , adjust
242 , adjustWithKey
243 , update
244 , updateWithKey
245 , updateLookupWithKey
246 , alter
247 , unionWith
248 , unionWithKey
249 , unionsWith
250 , differenceWith
251 , differenceWithKey
252 , intersectionWith
253 , intersectionWithKey
254 , mergeWithKey
255 , map
256 , mapWithKey
257 , mapAccum
258 , mapAccumWithKey
259 , mapAccumRWithKey
260 , mapKeysWith
261 , fromSet
262 , fromList
263 , fromListWith
264 , fromListWithKey
265 , fromAscList
266 , fromAscListWith
267 , fromAscListWithKey
268 , fromDistinctAscList
269 , mapMaybe
270 , mapMaybeWithKey
271 , mapEither
272 , mapEitherWithKey
273 , updateAt
274 , updateMin
275 , updateMax
276 , updateMinWithKey
277 , updateMaxWithKey
278 )
279 import qualified Data.Set.Base as Set
280 import Data.Utils.StrictFold
281 import Data.Utils.StrictPair
282
283 import Data.Bits (shiftL, shiftR)
284 #if __GLASGOW_HASKELL__ >= 709
285 import Data.Coerce
286 #endif
287
288
289 -- $strictness
290 --
291 -- This module satisfies the following strictness properties:
292 --
293 -- 1. Key arguments are evaluated to WHNF;
294 --
295 -- 2. Keys and values are evaluated to WHNF before they are stored in
296 -- the map.
297 --
298 -- Here's an example illustrating the first property:
299 --
300 -- > delete undefined m == undefined
301 --
302 -- Here are some examples that illustrate the second property:
303 --
304 -- > map (\ v -> undefined) m == undefined -- m is not empty
305 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
306
307 {--------------------------------------------------------------------
308 Query
309 --------------------------------------------------------------------}
310
311 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
312 -- the value at key @k@ or returns default value @def@
313 -- when the key is not in the map.
314 --
315 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
316 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
317
318 -- See Map.Base.Note: Local 'go' functions and capturing
319 findWithDefault :: Ord k => a -> k -> Map k a -> a
320 findWithDefault def k = k `seq` go
321 where
322 go Tip = def
323 go (Bin _ kx x l r) = case compare k kx of
324 LT -> go l
325 GT -> go r
326 EQ -> x
327 #if __GLASGOW_HASKELL__
328 {-# INLINABLE findWithDefault #-}
329 #else
330 {-# INLINE findWithDefault #-}
331 #endif
332
333 {--------------------------------------------------------------------
334 Construction
335 --------------------------------------------------------------------}
336
337 -- | /O(1)/. A map with a single element.
338 --
339 -- > singleton 1 'a' == fromList [(1, 'a')]
340 -- > size (singleton 1 'a') == 1
341
342 singleton :: k -> a -> Map k a
343 singleton k x = x `seq` Bin 1 k x Tip Tip
344 {-# INLINE singleton #-}
345
346 {--------------------------------------------------------------------
347 Insertion
348 --------------------------------------------------------------------}
349 -- | /O(log n)/. Insert a new key and value in the map.
350 -- If the key is already present in the map, the associated value is
351 -- replaced with the supplied value. 'insert' is equivalent to
352 -- @'insertWith' 'const'@.
353 --
354 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
355 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
356 -- > insert 5 'x' empty == singleton 5 'x'
357
358 -- See Map.Base.Note: Type of local 'go' function
359 insert :: Ord k => k -> a -> Map k a -> Map k a
360 insert = go
361 where
362 go :: Ord k => k -> a -> Map k a -> Map k a
363 go !kx !x Tip = singleton kx x
364 go kx x (Bin sz ky y l r) =
365 case compare kx ky of
366 LT -> balanceL ky y (go kx x l) r
367 GT -> balanceR ky y l (go kx x r)
368 EQ -> Bin sz kx x l r
369 #if __GLASGOW_HASKELL__
370 {-# INLINABLE insert #-}
371 #else
372 {-# INLINE insert #-}
373 #endif
374
375 -- | /O(log n)/. Insert with a function, combining new value and old value.
376 -- @'insertWith' f key value mp@
377 -- will insert the pair (key, value) into @mp@ if key does
378 -- not exist in the map. If the key does exist, the function will
379 -- insert the pair @(key, f new_value old_value)@.
380 --
381 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
382 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
383 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
384
385 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
386 insertWith f = insertWithKey (\_ x' y' -> f x' y')
387 #if __GLASGOW_HASKELL__
388 {-# INLINABLE insertWith #-}
389 #else
390 {-# INLINE insertWith #-}
391 #endif
392
393 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
394 -- @'insertWithKey' f key value mp@
395 -- will insert the pair (key, value) into @mp@ if key does
396 -- not exist in the map. If the key does exist, the function will
397 -- insert the pair @(key,f key new_value old_value)@.
398 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
399 --
400 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
401 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
402 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
403 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
404
405 -- See Map.Base.Note: Type of local 'go' function
406 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
407 insertWithKey = go
408 where
409 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
410 -- Forcing `kx` may look redundant, but it's possible `compare` will
411 -- be lazy.
412 go _ !kx x Tip = singleton kx x
413 go f kx x (Bin sy ky y l r) =
414 case compare kx ky of
415 LT -> balanceL ky y (go f kx x l) r
416 GT -> balanceR ky y l (go f kx x r)
417 EQ -> let !x' = f kx x y
418 in Bin sy kx x' l r
419 #if __GLASGOW_HASKELL__
420 {-# INLINABLE insertWithKey #-}
421 #else
422 {-# INLINE insertWithKey #-}
423 #endif
424
425 -- | /O(log n)/. Combines insert operation with old value retrieval.
426 -- The expression (@'insertLookupWithKey' f k x map@)
427 -- is a pair where the first element is equal to (@'lookup' k map@)
428 -- and the second element equal to (@'insertWithKey' f k x map@).
429 --
430 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
431 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
432 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
433 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
434 --
435 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
436 --
437 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
438 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
439 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
440
441 -- See Map.Base.Note: Type of local 'go' function
442 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
443 -> (Maybe a, Map k a)
444 insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0
445 where
446 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a)
447 go _ !kx x Tip = Nothing :*: singleton kx x
448 go f kx x (Bin sy ky y l r) =
449 case compare kx ky of
450 LT -> let (found :*: l') = go f kx x l
451 in found :*: balanceL ky y l' r
452 GT -> let (found :*: r') = go f kx x r
453 in found :*: balanceR ky y l r'
454 EQ -> let x' = f kx x y
455 in x' `seq` (Just y :*: Bin sy kx x' l r)
456 #if __GLASGOW_HASKELL__
457 {-# INLINABLE insertLookupWithKey #-}
458 #else
459 {-# INLINE insertLookupWithKey #-}
460 #endif
461
462 {--------------------------------------------------------------------
463 Deletion
464 --------------------------------------------------------------------}
465
466 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
467 -- When the key is not
468 -- a member of the map, the original map is returned.
469 --
470 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
471 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
472 -- > adjust ("new " ++) 7 empty == empty
473
474 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
475 adjust f = adjustWithKey (\_ x -> f x)
476 #if __GLASGOW_HASKELL__
477 {-# INLINABLE adjust #-}
478 #else
479 {-# INLINE adjust #-}
480 #endif
481
482 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
483 -- a member of the map, the original map is returned.
484 --
485 -- > let f key x = (show key) ++ ":new " ++ x
486 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
487 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
488 -- > adjustWithKey f 7 empty == empty
489
490 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
491 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
492 #if __GLASGOW_HASKELL__
493 {-# INLINABLE adjustWithKey #-}
494 #else
495 {-# INLINE adjustWithKey #-}
496 #endif
497
498 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
499 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
500 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
501 --
502 -- > let f x = if x == "a" then Just "new a" else Nothing
503 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
504 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
505 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
506
507 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
508 update f = updateWithKey (\_ x -> f x)
509 #if __GLASGOW_HASKELL__
510 {-# INLINABLE update #-}
511 #else
512 {-# INLINE update #-}
513 #endif
514
515 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
516 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
517 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
518 -- to the new value @y@.
519 --
520 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
521 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
522 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
523 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
524
525 -- See Map.Base.Note: Type of local 'go' function
526 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
527 updateWithKey = go
528 where
529 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
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__
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 go _ !_ Tip = (Nothing :*: Tip)
559 go f k (Bin sx kx x l r) =
560 case compare k kx of
561 LT -> let (found :*: l') = go f k l
562 in found :*: balanceR kx x l' r
563 GT -> let (found :*: r') = go f k r
564 in found :*: balanceL kx x l r'
565 EQ -> case f kx x of
566 Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
567 Nothing -> (Just x :*: glue l r)
568 #if __GLASGOW_HASKELL__
569 {-# INLINABLE updateLookupWithKey #-}
570 #else
571 {-# INLINE updateLookupWithKey #-}
572 #endif
573
574 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
575 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
576 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
577 --
578 -- > let f _ = Nothing
579 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
580 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
581 -- >
582 -- > let f _ = Just "c"
583 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
584 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
585
586 -- See Map.Base.Note: Type of local 'go' function
587 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
588 alter = go
589 where
590 go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
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__
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__
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__
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__
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__
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__
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__
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__
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 -- 'Map'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__
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 go !_ t [] = t
1062 go _ t [(kx, x)] = x `seq` insertMax kx x t
1063 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1064 | otherwise = case create s xss of
1065 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1066 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1067
1068 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1069 -- represent not yet processed elements and only one of them can be nonempty.
1070 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1071 -- and must be inserted using fromList'. Otherwise the keys have been
1072 -- ordered so far.
1073 create !_ [] = (Tip, [], [])
1074 create s xs@(xp : xss)
1075 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1076 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1077 | otherwise = case create (s `shiftR` 1) xs of
1078 res@(_, [], _) -> res
1079 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1080 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1081 | otherwise -> case create (s `shiftR` 1) yss of
1082 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1083 #if __GLASGOW_HASKELL__
1084 {-# INLINABLE fromList #-}
1085 #endif
1086
1087 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1088 --
1089 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1090 -- > fromListWith (++) [] == empty
1091
1092 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1093 fromListWith f xs
1094 = fromListWithKey (\_ x y -> f x y) xs
1095 #if __GLASGOW_HASKELL__
1096 {-# INLINABLE fromListWith #-}
1097 #endif
1098
1099 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1100 --
1101 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1102 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1103 -- > fromListWithKey f [] == empty
1104
1105 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1106 fromListWithKey f xs
1107 = foldlStrict ins empty xs
1108 where
1109 ins t (k,x) = insertWithKey f k x t
1110 #if __GLASGOW_HASKELL__
1111 {-# INLINABLE fromListWithKey #-}
1112 #endif
1113
1114 {--------------------------------------------------------------------
1115 Building trees from ascending/descending lists can be done in linear time.
1116
1117 Note that if [xs] is ascending that:
1118 fromAscList xs == fromList xs
1119 fromAscListWith f xs == fromListWith f xs
1120 --------------------------------------------------------------------}
1121 -- | /O(n)/. Build a map from an ascending list in linear time.
1122 -- /The precondition (input list is ascending) is not checked./
1123 --
1124 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1125 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1126 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1127 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1128
1129 fromAscList :: Eq k => [(k,a)] -> Map k a
1130 fromAscList xs
1131 = fromAscListWithKey (\_ x _ -> x) xs
1132 #if __GLASGOW_HASKELL__
1133 {-# INLINABLE fromAscList #-}
1134 #endif
1135
1136 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1137 -- /The precondition (input list is ascending) is not checked./
1138 --
1139 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1140 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1141 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1142
1143 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1144 fromAscListWith f xs
1145 = fromAscListWithKey (\_ x y -> f x y) xs
1146 #if __GLASGOW_HASKELL__
1147 {-# INLINABLE fromAscListWith #-}
1148 #endif
1149
1150 -- | /O(n)/. Build a map from an ascending list in linear time with a
1151 -- combining function for equal keys.
1152 -- /The precondition (input list is ascending) is not checked./
1153 --
1154 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1155 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1156 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1157 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1158
1159 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1160 fromAscListWithKey f xs
1161 = fromDistinctAscList (combineEq f xs)
1162 where
1163 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1164 combineEq _ xs'
1165 = case xs' of
1166 [] -> []
1167 [x] -> [x]
1168 (x:xx) -> combineEq' x xx
1169
1170 combineEq' z [] = [z]
1171 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1172 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1173 | otherwise = z:combineEq' x xs'
1174 #if __GLASGOW_HASKELL__
1175 {-# INLINABLE fromAscListWithKey #-}
1176 #endif
1177
1178 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1179 -- /The precondition is not checked./
1180 --
1181 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1182 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1183 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1184
1185 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1186 -- create, it is not inlined, so we inline it manually.
1187 fromDistinctAscList :: [(k,a)] -> Map k a
1188 fromDistinctAscList [] = Tip
1189 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1190 where
1191 go !_ t [] = t
1192 go s l ((kx, x) : xs) = case create s xs of
1193 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1194
1195 create !_ [] = (Tip, [])
1196 create s xs@(x' : xs')
1197 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1198 | otherwise = case create (s `shiftR` 1) xs of
1199 res@(_, []) -> res
1200 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1201 (r, zs) -> y `seq` (link ky y l r, zs)