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