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