Speed up adjust and adjustWithKey
[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 = go
492 where
493 go :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
494 go _ !_ Tip = Tip
495 go f k (Bin sx kx x l r) =
496 case compare k kx of
497 LT -> Bin sx kx x (go f k l) r
498 GT -> Bin sx kx x l (go f k r)
499 EQ -> Bin sx kx x' l r
500 where !x' = f kx x
501 #if __GLASGOW_HASKELL__
502 {-# INLINABLE adjustWithKey #-}
503 #else
504 {-# INLINE adjustWithKey #-}
505 #endif
506
507 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
508 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
509 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
510 --
511 -- > let f x = if x == "a" then Just "new a" else Nothing
512 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
513 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
514 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
515
516 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
517 update f = updateWithKey (\_ x -> f x)
518 #if __GLASGOW_HASKELL__
519 {-# INLINABLE update #-}
520 #else
521 {-# INLINE update #-}
522 #endif
523
524 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
525 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
526 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
527 -- to the new value @y@.
528 --
529 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
530 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
531 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
532 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
533
534 -- See Map.Base.Note: Type of local 'go' function
535 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
536 updateWithKey = go
537 where
538 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
539 go _ !_ Tip = Tip
540 go f k(Bin sx kx x l r) =
541 case compare k kx of
542 LT -> balanceR kx x (go f k l) r
543 GT -> balanceL kx x l (go f k r)
544 EQ -> case f kx x of
545 Just x' -> x' `seq` Bin sx kx x' l r
546 Nothing -> glue l r
547 #if __GLASGOW_HASKELL__
548 {-# INLINABLE updateWithKey #-}
549 #else
550 {-# INLINE updateWithKey #-}
551 #endif
552
553 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
554 -- The function returns changed value, if it is updated.
555 -- Returns the original key value if the map entry is deleted.
556 --
557 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
558 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
559 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
560 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
561
562 -- See Map.Base.Note: Type of local 'go' function
563 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
564 updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0
565 where
566 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
567 go _ !_ Tip = (Nothing :*: Tip)
568 go f k (Bin sx kx x l r) =
569 case compare k kx of
570 LT -> let (found :*: l') = go f k l
571 in found :*: balanceR kx x l' r
572 GT -> let (found :*: r') = go f k r
573 in found :*: balanceL kx x l r'
574 EQ -> case f kx x of
575 Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
576 Nothing -> (Just x :*: glue l r)
577 #if __GLASGOW_HASKELL__
578 {-# INLINABLE updateLookupWithKey #-}
579 #else
580 {-# INLINE updateLookupWithKey #-}
581 #endif
582
583 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
584 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
585 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
586 --
587 -- > let f _ = Nothing
588 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
589 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
590 -- >
591 -- > let f _ = Just "c"
592 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
593 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
594
595 -- See Map.Base.Note: Type of local 'go' function
596 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
597 alter = go
598 where
599 go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
600 go f !k Tip = case f Nothing of
601 Nothing -> Tip
602 Just x -> singleton k x
603
604 go f k (Bin sx kx x l r) = case compare k kx of
605 LT -> balance kx x (go f k l) r
606 GT -> balance kx x l (go f k r)
607 EQ -> case f (Just x) of
608 Just x' -> x' `seq` Bin sx kx x' l r
609 Nothing -> glue l r
610 #if __GLASGOW_HASKELL__
611 {-# INLINABLE alter #-}
612 #else
613 {-# INLINE alter #-}
614 #endif
615
616 {--------------------------------------------------------------------
617 Indexing
618 --------------------------------------------------------------------}
619
620 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
621 -- invalid index is used.
622 --
623 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
624 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
625 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
626 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
627 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
628 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
629 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
630 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
631
632 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
633 updateAt f i t = i `seq`
634 case t of
635 Tip -> error "Map.updateAt: index out of range"
636 Bin sx kx x l r -> case compare i sizeL of
637 LT -> balanceR kx x (updateAt f i l) r
638 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
639 EQ -> case f kx x of
640 Just x' -> x' `seq` Bin sx kx x' l r
641 Nothing -> glue l r
642 where
643 sizeL = size l
644
645 {--------------------------------------------------------------------
646 Minimal, Maximal
647 --------------------------------------------------------------------}
648
649 -- | /O(log n)/. Update the value at the minimal key.
650 --
651 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
652 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
653
654 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
655 updateMin f m
656 = updateMinWithKey (\_ x -> f x) m
657
658 -- | /O(log n)/. Update the value at the maximal key.
659 --
660 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
661 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
662
663 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
664 updateMax f m
665 = updateMaxWithKey (\_ x -> f x) m
666
667
668 -- | /O(log n)/. Update the value at the minimal key.
669 --
670 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
671 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
672
673 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
674 updateMinWithKey _ Tip = Tip
675 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
676 Nothing -> r
677 Just x' -> x' `seq` Bin sx kx x' Tip r
678 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
679
680 -- | /O(log n)/. Update the value at the maximal key.
681 --
682 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
683 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
684
685 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
686 updateMaxWithKey _ Tip = Tip
687 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
688 Nothing -> l
689 Just x' -> x' `seq` Bin sx kx x' l Tip
690 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
691
692 {--------------------------------------------------------------------
693 Union.
694 --------------------------------------------------------------------}
695
696 -- | The union of a list of maps, with a combining operation:
697 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
698 --
699 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
700 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
701
702 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
703 unionsWith f ts
704 = foldlStrict (unionWith f) empty ts
705 #if __GLASGOW_HASKELL__
706 {-# INLINABLE unionsWith #-}
707 #endif
708
709 {--------------------------------------------------------------------
710 Union with a combining function
711 --------------------------------------------------------------------}
712 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
713 --
714 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
715
716 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
717 unionWith f m1 m2
718 = unionWithKey (\_ x y -> f x y) m1 m2
719 #if __GLASGOW_HASKELL__
720 {-# INLINABLE unionWith #-}
721 #endif
722
723 -- | /O(n+m)/.
724 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
725 --
726 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
727 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
728
729 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
730 unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
731 #if __GLASGOW_HASKELL__
732 {-# INLINABLE unionWithKey #-}
733 #endif
734
735 {--------------------------------------------------------------------
736 Difference
737 --------------------------------------------------------------------}
738
739 -- | /O(n+m)/. Difference with a combining function.
740 -- When two equal keys are
741 -- encountered, the combining function is applied to the values of these keys.
742 -- If it returns 'Nothing', the element is discarded (proper set difference). If
743 -- it returns (@'Just' y@), the element is updated with a new value @y@.
744 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
745 --
746 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
747 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
748 -- > == singleton 3 "b:B"
749
750 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
751 differenceWith f m1 m2
752 = differenceWithKey (\_ x y -> f x y) m1 m2
753 #if __GLASGOW_HASKELL__
754 {-# INLINABLE differenceWith #-}
755 #endif
756
757 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
758 -- encountered, the combining function is applied to the key and both values.
759 -- If it returns 'Nothing', the element is discarded (proper set difference). If
760 -- it returns (@'Just' y@), the element is updated with a new value @y@.
761 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
762 --
763 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
764 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
765 -- > == singleton 3 "3:b|B"
766
767 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
768 differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
769 #if __GLASGOW_HASKELL__
770 {-# INLINABLE differenceWithKey #-}
771 #endif
772
773
774 {--------------------------------------------------------------------
775 Intersection
776 --------------------------------------------------------------------}
777
778 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
779 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
780 --
781 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
782
783 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
784 intersectionWith f m1 m2
785 = intersectionWithKey (\_ x y -> f x y) m1 m2
786 #if __GLASGOW_HASKELL__
787 {-# INLINABLE intersectionWith #-}
788 #endif
789
790 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
791 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
792 --
793 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
794 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
795
796
797 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
798 intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
799 #if __GLASGOW_HASKELL__
800 {-# INLINABLE intersectionWithKey #-}
801 #endif
802
803
804 {--------------------------------------------------------------------
805 MergeWithKey
806 --------------------------------------------------------------------}
807
808 -- | /O(n+m)/. A high-performance universal combining function. This function
809 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
810 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
811 -- used to define other custom combine functions.
812 --
813 -- Please make sure you know what is going on when using 'mergeWithKey',
814 -- otherwise you can be surprised by unexpected code growth or even
815 -- corruption of the data structure.
816 --
817 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
818 -- site. You should therefore use 'mergeWithKey' only to define your custom
819 -- combining functions. For example, you could define 'unionWithKey',
820 -- 'differenceWithKey' and 'intersectionWithKey' as
821 --
822 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
823 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
824 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
825 --
826 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
827 -- 'Map's is created, such that
828 --
829 -- * if a key is present in both maps, it is passed with both corresponding
830 -- values to the @combine@ function. Depending on the result, the key is either
831 -- present in the result with specified value, or is left out;
832 --
833 -- * a nonempty subtree present only in the first map is passed to @only1@ and
834 -- the output is added to the result;
835 --
836 -- * a nonempty subtree present only in the second map is passed to @only2@ and
837 -- the output is added to the result.
838 --
839 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
840 -- The values can be modified arbitrarily. Most common variants of @only1@ and
841 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
842 -- @'filterWithKey' f@ could be used for any @f@.
843
844 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
845 -> Map k a -> Map k b -> Map k c
846 mergeWithKey f g1 g2 = go
847 where
848 go Tip t2 = g2 t2
849 go t1 Tip = g1 t1
850 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
851
852 hedgeMerge _ _ t1 Tip = g1 t1
853 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
854 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
855 (found, trim_t2) = trimLookupLo kx bhi t2
856 r' = hedgeMerge bmi bhi r trim_t2
857 in case found of
858 Nothing -> case g1 (singleton kx x) of
859 Tip -> merge l' r'
860 (Bin _ _ x' Tip Tip) -> link kx x' l' r'
861 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
862 Just x2 -> case f kx x x2 of
863 Nothing -> merge l' r'
864 Just x' -> x' `seq` link kx x' l' r'
865 where bmi = JustS kx
866 {-# INLINE mergeWithKey #-}
867
868 {--------------------------------------------------------------------
869 Filter and partition
870 --------------------------------------------------------------------}
871
872 -- | /O(n)/. Map values and collect the 'Just' results.
873 --
874 -- > let f x = if x == "a" then Just "new a" else Nothing
875 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
876
877 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
878 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
879
880 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
881 --
882 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
883 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
884
885 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
886 mapMaybeWithKey _ Tip = Tip
887 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
888 Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
889 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
890
891 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
892 --
893 -- > let f a = if a < "c" then Left a else Right a
894 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
895 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
896 -- >
897 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
898 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
899
900 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
901 mapEither f m
902 = mapEitherWithKey (\_ x -> f x) m
903
904 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
905 --
906 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
907 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
908 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
909 -- >
910 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
911 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
912
913 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
914 mapEitherWithKey f0 t0 = toPair $ go f0 t0
915 where
916 go _ Tip = (Tip :*: Tip)
917 go f (Bin _ kx x l r) = case f kx x of
918 Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
919 Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
920 where
921 (l1 :*: l2) = go f l
922 (r1 :*: r2) = go f r
923
924 {--------------------------------------------------------------------
925 Mapping
926 --------------------------------------------------------------------}
927 -- | /O(n)/. Map a function over all values in the map.
928 --
929 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
930
931 map :: (a -> b) -> Map k a -> Map k b
932 map _ Tip = Tip
933 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)
934 #ifdef __GLASGOW_HASKELL__
935 {-# NOINLINE [1] map #-}
936 {-# RULES
937 "map/map" forall f g xs . map f (map g xs) = map (f . g) xs
938 #-}
939 #endif
940 #if __GLASGOW_HASKELL__ >= 709
941 -- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
942 {-# RULES
943 "mapSeq/coerce" map coerce = coerce
944 #-}
945 #endif
946
947 -- | /O(n)/. Map a function over all values in the map.
948 --
949 -- > let f key x = (show key) ++ ":" ++ x
950 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
951
952 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
953 mapWithKey _ Tip = Tip
954 mapWithKey f (Bin sx kx x l r) =
955 let x' = f kx x
956 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
957
958 #ifdef __GLASGOW_HASKELL__
959 {-# NOINLINE [1] mapWithKey #-}
960 {-# RULES
961 "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
962 mapWithKey (\k a -> f k (g k a)) xs
963 "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
964 mapWithKey (\k a -> f k (g a)) xs
965 "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
966 mapWithKey (\k a -> f (g k a)) xs
967 #-}
968 #endif
969
970 -- | /O(n)/. The function 'mapAccum' threads an accumulating
971 -- argument through the map in ascending order of keys.
972 --
973 -- > let f a b = (a ++ b, b ++ "X")
974 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
975
976 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
977 mapAccum f a m
978 = mapAccumWithKey (\a' _ x' -> f a' x') a m
979
980 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
981 -- argument through the map in ascending order of keys.
982 --
983 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
984 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
985
986 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
987 mapAccumWithKey f a t
988 = mapAccumL f a t
989
990 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
991 -- argument through the map in ascending order of keys.
992 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
993 mapAccumL _ a Tip = (a,Tip)
994 mapAccumL f a (Bin sx kx x l r) =
995 let (a1,l') = mapAccumL f a l
996 (a2,x') = f a1 kx x
997 (a3,r') = mapAccumL f a2 r
998 in x' `seq` (a3,Bin sx kx x' l' r')
999
1000 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1001 -- argument through the map in descending order of keys.
1002 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1003 mapAccumRWithKey _ a Tip = (a,Tip)
1004 mapAccumRWithKey f a (Bin sx kx x l r) =
1005 let (a1,r') = mapAccumRWithKey f a r
1006 (a2,x') = f a1 kx x
1007 (a3,l') = mapAccumRWithKey f a2 l
1008 in x' `seq` (a3,Bin sx kx x' l' r')
1009
1010 -- | /O(n*log n)/.
1011 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1012 --
1013 -- The size of the result may be smaller if @f@ maps two or more distinct
1014 -- keys to the same new key. In this case the associated values will be
1015 -- combined using @c@.
1016 --
1017 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1018 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1019
1020 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1021 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1022 #if __GLASGOW_HASKELL__
1023 {-# INLINABLE mapKeysWith #-}
1024 #endif
1025
1026 {--------------------------------------------------------------------
1027 Conversions
1028 --------------------------------------------------------------------}
1029
1030 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1031 -- computes its value.
1032 --
1033 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1034 -- > fromSet undefined Data.Set.empty == empty
1035
1036 fromSet :: (k -> a) -> Set.Set k -> Map k a
1037 fromSet _ Set.Tip = Tip
1038 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)
1039
1040 {--------------------------------------------------------------------
1041 Lists
1042 use [foldlStrict] to reduce demand on the control-stack
1043 --------------------------------------------------------------------}
1044 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1045 -- If the list contains more than one value for the same key, the last value
1046 -- for the key is retained.
1047 --
1048 -- If the keys of the list are ordered, linear-time implementation is used,
1049 -- with the performance equal to 'fromDistinctAscList'.
1050 --
1051 -- > fromList [] == empty
1052 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1053 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1054
1055 -- For some reason, when 'singleton' is used in fromList or in
1056 -- create, it is not inlined, so we inline it manually.
1057 fromList :: Ord k => [(k,a)] -> Map k a
1058 fromList [] = Tip
1059 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1060 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1061 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1062 where
1063 not_ordered _ [] = False
1064 not_ordered kx ((ky,_) : _) = kx >= ky
1065 {-# INLINE not_ordered #-}
1066
1067 fromList' t0 xs = foldlStrict ins t0 xs
1068 where ins t (k,x) = insert k x t
1069
1070 go !_ t [] = t
1071 go _ t [(kx, x)] = x `seq` insertMax kx x t
1072 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1073 | otherwise = case create s xss of
1074 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1075 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1076
1077 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1078 -- represent not yet processed elements and only one of them can be nonempty.
1079 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1080 -- and must be inserted using fromList'. Otherwise the keys have been
1081 -- ordered so far.
1082 create !_ [] = (Tip, [], [])
1083 create s xs@(xp : xss)
1084 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1085 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1086 | otherwise = case create (s `shiftR` 1) xs of
1087 res@(_, [], _) -> res
1088 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1089 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1090 | otherwise -> case create (s `shiftR` 1) yss of
1091 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1092 #if __GLASGOW_HASKELL__
1093 {-# INLINABLE fromList #-}
1094 #endif
1095
1096 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1097 --
1098 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1099 -- > fromListWith (++) [] == empty
1100
1101 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1102 fromListWith f xs
1103 = fromListWithKey (\_ x y -> f x y) xs
1104 #if __GLASGOW_HASKELL__
1105 {-# INLINABLE fromListWith #-}
1106 #endif
1107
1108 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1109 --
1110 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1111 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1112 -- > fromListWithKey f [] == empty
1113
1114 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1115 fromListWithKey f xs
1116 = foldlStrict ins empty xs
1117 where
1118 ins t (k,x) = insertWithKey f k x t
1119 #if __GLASGOW_HASKELL__
1120 {-# INLINABLE fromListWithKey #-}
1121 #endif
1122
1123 {--------------------------------------------------------------------
1124 Building trees from ascending/descending lists can be done in linear time.
1125
1126 Note that if [xs] is ascending that:
1127 fromAscList xs == fromList xs
1128 fromAscListWith f xs == fromListWith f xs
1129 --------------------------------------------------------------------}
1130 -- | /O(n)/. Build a map from an ascending list in linear time.
1131 -- /The precondition (input list is ascending) is not checked./
1132 --
1133 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1134 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1135 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1136 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1137
1138 fromAscList :: Eq k => [(k,a)] -> Map k a
1139 fromAscList xs
1140 = fromAscListWithKey (\_ x _ -> x) xs
1141 #if __GLASGOW_HASKELL__
1142 {-# INLINABLE fromAscList #-}
1143 #endif
1144
1145 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1146 -- /The precondition (input list is ascending) is not checked./
1147 --
1148 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1149 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1150 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1151
1152 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1153 fromAscListWith f xs
1154 = fromAscListWithKey (\_ x y -> f x y) xs
1155 #if __GLASGOW_HASKELL__
1156 {-# INLINABLE fromAscListWith #-}
1157 #endif
1158
1159 -- | /O(n)/. Build a map from an ascending list in linear time with a
1160 -- combining function for equal keys.
1161 -- /The precondition (input list is ascending) is not checked./
1162 --
1163 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1164 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1165 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1166 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1167
1168 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1169 fromAscListWithKey f xs
1170 = fromDistinctAscList (combineEq f xs)
1171 where
1172 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1173 combineEq _ xs'
1174 = case xs' of
1175 [] -> []
1176 [x] -> [x]
1177 (x:xx) -> combineEq' x xx
1178
1179 combineEq' z [] = [z]
1180 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1181 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1182 | otherwise = z:combineEq' x xs'
1183 #if __GLASGOW_HASKELL__
1184 {-# INLINABLE fromAscListWithKey #-}
1185 #endif
1186
1187 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1188 -- /The precondition is not checked./
1189 --
1190 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1191 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1192 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1193
1194 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1195 -- create, it is not inlined, so we inline it manually.
1196 fromDistinctAscList :: [(k,a)] -> Map k a
1197 fromDistinctAscList [] = Tip
1198 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1199 where
1200 go !_ t [] = t
1201 go s l ((kx, x) : xs) = case create s xs of
1202 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1203
1204 create !_ [] = (Tip, [])
1205 create s xs@(x' : xs')
1206 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1207 | otherwise = case create (s `shiftR` 1) xs of
1208 res@(_, []) -> res
1209 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1210 (r, zs) -> y `seq` (link ky y l r, zs)