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