Use Safe Haskell for GHC >= 7.2
[packages/containers.git] / Data / Map.hs
1 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 701
2 {-# LANGUAGE Safe #-}
3 #endif
4 {-# LANGUAGE NoBangPatterns #-}
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module : Data.Map
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 (Map)
21 -- > import qualified Data.Map 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 (
58 -- * Map type
59 #if !defined(TESTING)
60 Map -- instance Eq,Show,Read
61 #else
62 Map(..) -- instance Eq,Show,Read
63 #endif
64
65 -- * Operators
66 , (!), (\\)
67
68 -- * Query
69 , null
70 , size
71 , member
72 , notMember
73 , lookup
74 , findWithDefault
75
76 -- * Construction
77 , empty
78 , singleton
79
80 -- ** Insertion
81 , insert
82 , insertWith
83 , insertWith'
84 , insertWithKey
85 , insertWithKey'
86 , insertLookupWithKey
87 , insertLookupWithKey'
88
89 -- ** Delete\/Update
90 , delete
91 , adjust
92 , adjustWithKey
93 , update
94 , updateWithKey
95 , updateLookupWithKey
96 , alter
97
98 -- * Combine
99
100 -- ** Union
101 , union
102 , unionWith
103 , unionWithKey
104 , unions
105 , unionsWith
106
107 -- ** Difference
108 , difference
109 , differenceWith
110 , differenceWithKey
111
112 -- ** Intersection
113 , intersection
114 , intersectionWith
115 , intersectionWithKey
116
117 -- * Traversal
118 -- ** Map
119 , map
120 , mapWithKey
121 , mapAccum
122 , mapAccumWithKey
123 , mapAccumRWithKey
124 , mapKeys
125 , mapKeysWith
126 , mapKeysMonotonic
127
128 -- * Folds
129 , foldr
130 , foldl
131 , foldrWithKey
132 , foldlWithKey
133 -- ** Strict folds
134 , foldr'
135 , foldl'
136 , foldrWithKey'
137 , foldlWithKey'
138 -- ** Legacy folds
139 , fold
140 , foldWithKey
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
216 ) where
217
218 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
219 import qualified Data.Set as Set
220 import qualified Data.List as List
221 import Data.Monoid (Monoid(..))
222 import Control.Applicative (Applicative(..), (<$>))
223 import Data.Traversable (Traversable(traverse))
224 import qualified Data.Foldable as Foldable
225 import Data.Typeable
226
227 #if __GLASGOW_HASKELL__
228 import Text.Read
229 import Data.Data
230 #endif
231
232 -- Use macros to define strictness of functions.
233 -- STRICT_x_OF_y denotes an y-ary function strict in the x-th parameter.
234 -- We do not use BangPatterns, because they are not in any standard and we
235 -- want the compilers to be compiled by as many compilers as possible.
236 #define STRICT_1_OF_2(fn) fn arg _ | arg `seq` False = undefined
237 #define STRICT_1_OF_3(fn) fn arg _ _ | arg `seq` False = undefined
238 #define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
239 #define STRICT_2_OF_4(fn) fn _ arg _ _ | arg `seq` False = undefined
240
241 {--------------------------------------------------------------------
242 Operators
243 --------------------------------------------------------------------}
244 infixl 9 !,\\ --
245
246 -- | /O(log n)/. Find the value at a key.
247 -- Calls 'error' when the element can not be found.
248 --
249 -- > fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map
250 -- > fromList [(5,'a'), (3,'b')] ! 5 == 'a'
251
252 (!) :: Ord k => Map k a -> k -> a
253 m ! k = find k m
254 {-# INLINE (!) #-}
255
256 -- | Same as 'difference'.
257 (\\) :: Ord k => Map k a -> Map k b -> Map k a
258 m1 \\ m2 = difference m1 m2
259 #if __GLASGOW_HASKELL__ >= 700
260 {-# INLINABLE (\\) #-}
261 #endif
262
263 {--------------------------------------------------------------------
264 Size balanced trees.
265 --------------------------------------------------------------------}
266 -- | A Map from keys @k@ to values @a@.
267 data Map k a = Tip
268 | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
269
270 type Size = Int
271
272 instance (Ord k) => Monoid (Map k v) where
273 mempty = empty
274 mappend = union
275 mconcat = unions
276
277 #if __GLASGOW_HASKELL__
278
279 {--------------------------------------------------------------------
280 A Data instance
281 --------------------------------------------------------------------}
282
283 -- This instance preserves data abstraction at the cost of inefficiency.
284 -- We omit reflection services for the sake of data abstraction.
285
286 instance (Data k, Data a, Ord k) => Data (Map k a) where
287 gfoldl f z m = z fromList `f` toList m
288 toConstr _ = error "toConstr"
289 gunfold _ _ = error "gunfold"
290 dataTypeOf _ = mkNoRepType "Data.Map.Map"
291 dataCast2 f = gcast2 f
292
293 #endif
294
295 {--------------------------------------------------------------------
296 Query
297 --------------------------------------------------------------------}
298 -- | /O(1)/. Is the map empty?
299 --
300 -- > Data.Map.null (empty) == True
301 -- > Data.Map.null (singleton 1 'a') == False
302
303 null :: Map k a -> Bool
304 null Tip = True
305 null (Bin {}) = False
306 #if __GLASGOW_HASKELL__ >= 700
307 {-# INLINABLE null #-}
308 #endif
309
310 -- | /O(1)/. The number of elements in the map.
311 --
312 -- > size empty == 0
313 -- > size (singleton 1 'a') == 1
314 -- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
315
316 size :: Map k a -> Int
317 size Tip = 0
318 size (Bin sz _ _ _ _) = sz
319 #if __GLASGOW_HASKELL__ >= 700
320 {-# INLINABLE size #-}
321 #endif
322
323
324 -- | /O(log n)/. Lookup the value at a key in the map.
325 --
326 -- The function will return the corresponding value as @('Just' value)@,
327 -- or 'Nothing' if the key isn't in the map.
328 --
329 -- An example of using @lookup@:
330 --
331 -- > import Prelude hiding (lookup)
332 -- > import Data.Map
333 -- >
334 -- > employeeDept = fromList([("John","Sales"), ("Bob","IT")])
335 -- > deptCountry = fromList([("IT","USA"), ("Sales","France")])
336 -- > countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")])
337 -- >
338 -- > employeeCurrency :: String -> Maybe String
339 -- > employeeCurrency name = do
340 -- > dept <- lookup name employeeDept
341 -- > country <- lookup dept deptCountry
342 -- > lookup country countryCurrency
343 -- >
344 -- > main = do
345 -- > putStrLn $ "John's currency: " ++ (show (employeeCurrency "John"))
346 -- > putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))
347 --
348 -- The output of this program:
349 --
350 -- > John's currency: Just "Euro"
351 -- > Pete's currency: Nothing
352
353 lookup :: Ord k => k -> Map k a -> Maybe a
354 lookup = go
355 where
356 STRICT_1_OF_2(go)
357 go _ Tip = Nothing
358 go k (Bin _ kx x l r) =
359 case compare k kx of
360 LT -> go k l
361 GT -> go k r
362 EQ -> Just x
363 #if __GLASGOW_HASKELL__ >= 700
364 {-# INLINABLE lookup #-}
365 #else
366 {-# INLINE lookup #-}
367 #endif
368
369 lookupAssoc :: Ord k => k -> Map k a -> Maybe (k,a)
370 lookupAssoc = go
371 where
372 STRICT_1_OF_2(go)
373 go _ Tip = Nothing
374 go k (Bin _ kx x l r) =
375 case compare k kx of
376 LT -> go k l
377 GT -> go k r
378 EQ -> Just (kx,x)
379 #if __GLASGOW_HASKELL__ >= 700
380 {-# INLINEABLE lookupAssoc #-}
381 #else
382 {-# INLINE lookupAssoc #-}
383 #endif
384
385 -- | /O(log n)/. Is the key a member of the map? See also 'notMember'.
386 --
387 -- > member 5 (fromList [(5,'a'), (3,'b')]) == True
388 -- > member 1 (fromList [(5,'a'), (3,'b')]) == False
389
390 member :: Ord k => k -> Map k a -> Bool
391 member k m = case lookup k m of
392 Nothing -> False
393 Just _ -> True
394 #if __GLASGOW_HASKELL__ >= 700
395 {-# INLINEABLE member #-}
396 #else
397 {-# INLINE member #-}
398 #endif
399
400 -- | /O(log n)/. Is the key not a member of the map? See also 'member'.
401 --
402 -- > notMember 5 (fromList [(5,'a'), (3,'b')]) == False
403 -- > notMember 1 (fromList [(5,'a'), (3,'b')]) == True
404
405 notMember :: Ord k => k -> Map k a -> Bool
406 notMember k m = not $ member k m
407 {-# INLINE notMember #-}
408
409 -- | /O(log n)/. Find the value at a key.
410 -- Calls 'error' when the element can not be found.
411 -- Consider using 'lookup' when elements may not be present.
412 find :: Ord k => k -> Map k a -> a
413 find k m = case lookup k m of
414 Nothing -> error "Map.find: element not in the map"
415 Just x -> x
416 #if __GLASGOW_HASKELL__ >= 700
417 {-# INLINABLE find #-}
418 #else
419 {-# INLINE find #-}
420 #endif
421
422 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
423 -- the value at key @k@ or returns default value @def@
424 -- when the key is not in the map.
425 --
426 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
427 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
428
429 findWithDefault :: Ord k => a -> k -> Map k a -> a
430 findWithDefault def k m = case lookup k m of
431 Nothing -> def
432 Just x -> x
433 #if __GLASGOW_HASKELL__ >= 700
434 {-# INLINABLE findWithDefault #-}
435 #else
436 {-# INLINE findWithDefault #-}
437 #endif
438
439 {--------------------------------------------------------------------
440 Construction
441 --------------------------------------------------------------------}
442 -- | /O(1)/. The empty map.
443 --
444 -- > empty == fromList []
445 -- > size empty == 0
446
447 empty :: Map k a
448 empty = Tip
449
450 -- | /O(1)/. A map with a single element.
451 --
452 -- > singleton 1 'a' == fromList [(1, 'a')]
453 -- > size (singleton 1 'a') == 1
454
455 singleton :: k -> a -> Map k a
456 singleton k x = Bin 1 k x Tip Tip
457
458 {--------------------------------------------------------------------
459 Insertion
460 --------------------------------------------------------------------}
461 -- | /O(log n)/. Insert a new key and value in the map.
462 -- If the key is already present in the map, the associated value is
463 -- replaced with the supplied value. 'insert' is equivalent to
464 -- @'insertWith' 'const'@.
465 --
466 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
467 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
468 -- > insert 5 'x' empty == singleton 5 'x'
469
470 insert :: Ord k => k -> a -> Map k a -> Map k a
471 insert = go
472 where
473 STRICT_1_OF_3(go)
474 go kx x Tip = singleton kx x
475 go kx x (Bin sz ky y l r) =
476 case compare kx ky of
477 LT -> balanceL ky y (go kx x l) r
478 GT -> balanceR ky y l (go kx x r)
479 EQ -> Bin sz kx x l r
480 #if __GLASGOW_HASKELL__ >= 700
481 {-# INLINEABLE insert #-}
482 #else
483 {-# INLINE insert #-}
484 #endif
485
486 -- | /O(log n)/. Insert with a function, combining new value and old value.
487 -- @'insertWith' f key value mp@
488 -- will insert the pair (key, value) into @mp@ if key does
489 -- not exist in the map. If the key does exist, the function will
490 -- insert the pair @(key, f new_value old_value)@.
491 --
492 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
493 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
494 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
495
496 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
497 insertWith f = insertWithKey (\_ x' y' -> f x' y')
498 {-# INLINE insertWith #-}
499
500 -- | Same as 'insertWith', but the combining function is applied strictly.
501 -- This is often the most desirable behavior.
502 --
503 -- For example, to update a counter:
504 --
505 -- > insertWith' (+) k 1 m
506 --
507 insertWith' :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
508 insertWith' f = insertWithKey' (\_ x' y' -> f x' y')
509 {-# INLINE insertWith' #-}
510
511 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
512 -- @'insertWithKey' f key value mp@
513 -- will insert the pair (key, value) into @mp@ if key does
514 -- not exist in the map. If the key does exist, the function will
515 -- insert the pair @(key,f key new_value old_value)@.
516 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
517 --
518 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
519 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
520 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
521 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
522
523 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
524 insertWithKey = go
525 where
526 STRICT_2_OF_4(go)
527 go _ kx x Tip = singleton kx x
528 go f kx x (Bin sy ky y l r) =
529 case compare kx ky of
530 LT -> balanceL ky y (go f kx x l) r
531 GT -> balanceR ky y l (go f kx x r)
532 EQ -> Bin sy kx (f kx x y) l r
533 #if __GLASGOW_HASKELL__ >= 700
534 {-# INLINEABLE insertWithKey #-}
535 #else
536 {-# INLINE insertWithKey #-}
537 #endif
538
539 -- | Same as 'insertWithKey', but the combining function is applied strictly.
540 insertWithKey' :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
541 insertWithKey' = go
542 where
543 STRICT_2_OF_4(go)
544 go _ kx x Tip = x `seq` singleton kx x
545 go f kx x (Bin sy ky y l r) =
546 case compare kx ky of
547 LT -> balanceL ky y (go f kx x l) r
548 GT -> balanceR ky y l (go f kx x r)
549 EQ -> let x' = f kx x y in x' `seq` (Bin sy kx x' l r)
550 #if __GLASGOW_HASKELL__ >= 700
551 {-# INLINEABLE insertWithKey' #-}
552 #else
553 {-# INLINE insertWithKey' #-}
554 #endif
555
556 -- | /O(log n)/. Combines insert operation with old value retrieval.
557 -- The expression (@'insertLookupWithKey' f k x map@)
558 -- is a pair where the first element is equal to (@'lookup' k map@)
559 -- and the second element equal to (@'insertWithKey' f k x map@).
560 --
561 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
562 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
563 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
564 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
565 --
566 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
567 --
568 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
569 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
570 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
571
572 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
573 -> (Maybe a, Map k a)
574 insertLookupWithKey = go
575 where
576 STRICT_2_OF_4(go)
577 go _ kx x Tip = (Nothing, singleton kx x)
578 go f kx x (Bin sy ky y l r) =
579 case compare kx ky of
580 LT -> let (found, l') = go f kx x l
581 in (found, balanceL ky y l' r)
582 GT -> let (found, r') = go f kx x r
583 in (found, balanceR ky y l r')
584 EQ -> (Just y, Bin sy kx (f kx x y) l r)
585 #if __GLASGOW_HASKELL__ >= 700
586 {-# INLINEABLE insertLookupWithKey #-}
587 #else
588 {-# INLINE insertLookupWithKey #-}
589 #endif
590
591 -- | /O(log n)/. A strict version of 'insertLookupWithKey'.
592 insertLookupWithKey' :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
593 -> (Maybe a, Map k a)
594 insertLookupWithKey' = go
595 where
596 STRICT_2_OF_4(go)
597 go _ kx x Tip = x `seq` (Nothing, singleton kx x)
598 go f kx x (Bin sy ky y l r) =
599 case compare kx ky of
600 LT -> let (found, l') = go f kx x l
601 in (found, balanceL ky y l' r)
602 GT -> let (found, r') = go f kx x r
603 in (found, balanceR ky y l r')
604 EQ -> let x' = f kx x y in x' `seq` (Just y, Bin sy kx x' l r)
605 #if __GLASGOW_HASKELL__ >= 700
606 {-# INLINEABLE insertLookupWithKey' #-}
607 #else
608 {-# INLINE insertLookupWithKey' #-}
609 #endif
610
611 {--------------------------------------------------------------------
612 Deletion
613 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
614 --------------------------------------------------------------------}
615 -- | /O(log n)/. Delete a key and its value from the map. When the key is not
616 -- a member of the map, the original map is returned.
617 --
618 -- > delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
619 -- > delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
620 -- > delete 5 empty == empty
621
622 delete :: Ord k => k -> Map k a -> Map k a
623 delete = go
624 where
625 STRICT_1_OF_2(go)
626 go _ Tip = Tip
627 go k (Bin _ kx x l r) =
628 case compare k kx of
629 LT -> balanceR kx x (go k l) r
630 GT -> balanceL kx x l (go k r)
631 EQ -> glue l r
632 #if __GLASGOW_HASKELL__ >= 700
633 {-# INLINEABLE delete #-}
634 #else
635 {-# INLINE delete #-}
636 #endif
637
638 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
639 -- When the key is not
640 -- a member of the map, the original map is returned.
641 --
642 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
643 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
644 -- > adjust ("new " ++) 7 empty == empty
645
646 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
647 adjust f = adjustWithKey (\_ x -> f x)
648 {-# INLINE adjust #-}
649
650 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
651 -- a member of the map, the original map is returned.
652 --
653 -- > let f key x = (show key) ++ ":new " ++ x
654 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
655 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
656 -- > adjustWithKey f 7 empty == empty
657
658 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
659 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
660 {-# INLINE adjustWithKey #-}
661
662 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
663 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
664 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
665 --
666 -- > let f x = if x == "a" then Just "new a" else Nothing
667 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
668 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
669 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
670
671 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
672 update f = updateWithKey (\_ x -> f x)
673 {-# INLINE update #-}
674
675 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
676 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
677 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
678 -- to the new value @y@.
679 --
680 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
681 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
682 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
683 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
684
685 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
686 updateWithKey = go
687 where
688 STRICT_2_OF_3(go)
689 go _ _ Tip = Tip
690 go f k(Bin sx kx x l r) =
691 case compare k kx of
692 LT -> balanceR kx x (go f k l) r
693 GT -> balanceL kx x l (go f k r)
694 EQ -> case f kx x of
695 Just x' -> Bin sx kx x' l r
696 Nothing -> glue l r
697 #if __GLASGOW_HASKELL__ >= 700
698 {-# INLINEABLE updateWithKey #-}
699 #else
700 {-# INLINE updateWithKey #-}
701 #endif
702
703 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
704 -- The function returns changed value, if it is updated.
705 -- Returns the original key value if the map entry is deleted.
706 --
707 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
708 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
709 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
710 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
711
712 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
713 updateLookupWithKey = go
714 where
715 STRICT_2_OF_3(go)
716 go _ _ Tip = (Nothing,Tip)
717 go f k (Bin sx kx x l r) =
718 case compare k kx of
719 LT -> let (found,l') = go f k l in (found,balanceR kx x l' r)
720 GT -> let (found,r') = go f k r in (found,balanceL kx x l r')
721 EQ -> case f kx x of
722 Just x' -> (Just x',Bin sx kx x' l r)
723 Nothing -> (Just x,glue l r)
724 #if __GLASGOW_HASKELL__ >= 700
725 {-# INLINEABLE updateLookupWithKey #-}
726 #else
727 {-# INLINE updateLookupWithKey #-}
728 #endif
729
730 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
731 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
732 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
733 --
734 -- > let f _ = Nothing
735 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
736 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
737 -- >
738 -- > let f _ = Just "c"
739 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
740 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
741
742 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
743 alter = go
744 where
745 STRICT_2_OF_3(go)
746 go f k Tip = case f Nothing of
747 Nothing -> Tip
748 Just x -> singleton k x
749
750 go f k (Bin sx kx x l r) = case compare k kx of
751 LT -> balance kx x (go f k l) r
752 GT -> balance kx x l (go f k r)
753 EQ -> case f (Just x) of
754 Just x' -> Bin sx kx x' l r
755 Nothing -> glue l r
756 #if __GLASGOW_HASKELL__ >= 700
757 {-# INLINEABLE alter #-}
758 #else
759 {-# INLINE alter #-}
760 #endif
761
762 {--------------------------------------------------------------------
763 Indexing
764 --------------------------------------------------------------------}
765 -- | /O(log n)/. Return the /index/ of a key. The index is a number from
766 -- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
767 -- the key is not a 'member' of the map.
768 --
769 -- > findIndex 2 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map
770 -- > findIndex 3 (fromList [(5,"a"), (3,"b")]) == 0
771 -- > findIndex 5 (fromList [(5,"a"), (3,"b")]) == 1
772 -- > findIndex 6 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map
773
774 findIndex :: Ord k => k -> Map k a -> Int
775 findIndex k t
776 = case lookupIndex k t of
777 Nothing -> error "Map.findIndex: element is not in the map"
778 Just idx -> idx
779 #if __GLASGOW_HASKELL__ >= 700
780 {-# INLINABLE findIndex #-}
781 #endif
782
783 -- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
784 -- /0/ up to, but not including, the 'size' of the map.
785 --
786 -- > isJust (lookupIndex 2 (fromList [(5,"a"), (3,"b")])) == False
787 -- > fromJust (lookupIndex 3 (fromList [(5,"a"), (3,"b")])) == 0
788 -- > fromJust (lookupIndex 5 (fromList [(5,"a"), (3,"b")])) == 1
789 -- > isJust (lookupIndex 6 (fromList [(5,"a"), (3,"b")])) == False
790
791 lookupIndex :: Ord k => k -> Map k a -> Maybe Int
792 lookupIndex k = lkp k 0
793 where
794 STRICT_1_OF_3(lkp)
795 STRICT_2_OF_3(lkp)
796 lkp _ _ Tip = Nothing
797 lkp key idx (Bin _ kx _ l r)
798 = case compare key kx of
799 LT -> lkp key idx l
800 GT -> lkp key (idx + size l + 1) r
801 EQ -> let idx' = idx + size l in idx' `seq` Just idx'
802 #if __GLASGOW_HASKELL__ >= 700
803 {-# INLINABLE lookupIndex #-}
804 #endif
805
806 -- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
807 -- invalid index is used.
808 --
809 -- > elemAt 0 (fromList [(5,"a"), (3,"b")]) == (3,"b")
810 -- > elemAt 1 (fromList [(5,"a"), (3,"b")]) == (5, "a")
811 -- > elemAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
812
813 elemAt :: Int -> Map k a -> (k,a)
814 STRICT_1_OF_2(elemAt)
815 elemAt _ Tip = error "Map.elemAt: index out of range"
816 elemAt i (Bin _ kx x l r)
817 = case compare i sizeL of
818 LT -> elemAt i l
819 GT -> elemAt (i-sizeL-1) r
820 EQ -> (kx,x)
821 where
822 sizeL = size l
823 #if __GLASGOW_HASKELL__ >= 700
824 {-# INLINABLE elemAt #-}
825 #endif
826
827 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
828 -- invalid index is used.
829 --
830 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
831 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
832 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
833 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
834 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
835 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
836 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
837 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
838
839 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
840 updateAt f i t = i `seq`
841 case t of
842 Tip -> error "Map.updateAt: index out of range"
843 Bin sx kx x l r -> case compare i sizeL of
844 LT -> balanceR kx x (updateAt f i l) r
845 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
846 EQ -> case f kx x of
847 Just x' -> Bin sx kx x' l r
848 Nothing -> glue l r
849 where
850 sizeL = size l
851 #if __GLASGOW_HASKELL__ >= 700
852 {-# INLINABLE updateAt #-}
853 #endif
854
855 -- | /O(log n)/. Delete the element at /index/.
856 -- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
857 --
858 -- > deleteAt 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
859 -- > deleteAt 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
860 -- > deleteAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
861 -- > deleteAt (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
862
863 deleteAt :: Int -> Map k a -> Map k a
864 deleteAt i m
865 = updateAt (\_ _ -> Nothing) i m
866 #if __GLASGOW_HASKELL__ >= 700
867 {-# INLINABLE deleteAt #-}
868 #endif
869
870
871 {--------------------------------------------------------------------
872 Minimal, Maximal
873 --------------------------------------------------------------------}
874 -- | /O(log n)/. The minimal key of the map. Calls 'error' if the map is empty.
875 --
876 -- > findMin (fromList [(5,"a"), (3,"b")]) == (3,"b")
877 -- > findMin empty Error: empty map has no minimal element
878
879 findMin :: Map k a -> (k,a)
880 findMin (Bin _ kx x Tip _) = (kx,x)
881 findMin (Bin _ _ _ l _) = findMin l
882 findMin Tip = error "Map.findMin: empty map has no minimal element"
883 #if __GLASGOW_HASKELL__ >= 700
884 {-# INLINABLE findMin #-}
885 #endif
886
887 -- | /O(log n)/. The maximal key of the map. Calls 'error' if the map is empty.
888 --
889 -- > findMax (fromList [(5,"a"), (3,"b")]) == (5,"a")
890 -- > findMax empty Error: empty map has no maximal element
891
892 findMax :: Map k a -> (k,a)
893 findMax (Bin _ kx x _ Tip) = (kx,x)
894 findMax (Bin _ _ _ _ r) = findMax r
895 findMax Tip = error "Map.findMax: empty map has no maximal element"
896 #if __GLASGOW_HASKELL__ >= 700
897 {-# INLINABLE findMax #-}
898 #endif
899
900 -- | /O(log n)/. Delete the minimal key. Returns an empty map if the map is empty.
901 --
902 -- > deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")]
903 -- > deleteMin empty == empty
904
905 deleteMin :: Map k a -> Map k a
906 deleteMin (Bin _ _ _ Tip r) = r
907 deleteMin (Bin _ kx x l r) = balanceR kx x (deleteMin l) r
908 deleteMin Tip = Tip
909 #if __GLASGOW_HASKELL__ >= 700
910 {-# INLINABLE deleteMin #-}
911 #endif
912
913 -- | /O(log n)/. Delete the maximal key. Returns an empty map if the map is empty.
914 --
915 -- > deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")]
916 -- > deleteMax empty == empty
917
918 deleteMax :: Map k a -> Map k a
919 deleteMax (Bin _ _ _ l Tip) = l
920 deleteMax (Bin _ kx x l r) = balanceL kx x l (deleteMax r)
921 deleteMax Tip = Tip
922 #if __GLASGOW_HASKELL__ >= 700
923 {-# INLINABLE deleteMax #-}
924 #endif
925
926 -- | /O(log n)/. Update the value at the minimal key.
927 --
928 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
929 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
930
931 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
932 updateMin f m
933 = updateMinWithKey (\_ x -> f x) m
934 #if __GLASGOW_HASKELL__ >= 700
935 {-# INLINABLE updateMin #-}
936 #endif
937
938 -- | /O(log n)/. Update the value at the maximal key.
939 --
940 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
941 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
942
943 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
944 updateMax f m
945 = updateMaxWithKey (\_ x -> f x) m
946 #if __GLASGOW_HASKELL__ >= 700
947 {-# INLINABLE updateMax #-}
948 #endif
949
950
951 -- | /O(log n)/. Update the value at the minimal key.
952 --
953 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
954 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
955
956 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
957 updateMinWithKey _ Tip = Tip
958 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
959 Nothing -> r
960 Just x' -> Bin sx kx x' Tip r
961 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
962 #if __GLASGOW_HASKELL__ >= 700
963 {-# INLINABLE updateMinWithKey #-}
964 #endif
965
966 -- | /O(log n)/. Update the value at the maximal key.
967 --
968 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
969 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
970
971 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
972 updateMaxWithKey _ Tip = Tip
973 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
974 Nothing -> l
975 Just x' -> Bin sx kx x' l Tip
976 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
977 #if __GLASGOW_HASKELL__ >= 700
978 {-# INLINABLE updateMaxWithKey #-}
979 #endif
980
981 -- | /O(log n)/. Retrieves the minimal (key,value) pair of the map, and
982 -- the map stripped of that element, or 'Nothing' if passed an empty map.
983 --
984 -- > minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
985 -- > minViewWithKey empty == Nothing
986
987 minViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
988 minViewWithKey Tip = Nothing
989 minViewWithKey x = Just (deleteFindMin x)
990 #if __GLASGOW_HASKELL__ >= 700
991 {-# INLINABLE minViewWithKey #-}
992 #endif
993
994 -- | /O(log n)/. Retrieves the maximal (key,value) pair of the map, and
995 -- the map stripped of that element, or 'Nothing' if passed an empty map.
996 --
997 -- > maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
998 -- > maxViewWithKey empty == Nothing
999
1000 maxViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
1001 maxViewWithKey Tip = Nothing
1002 maxViewWithKey x = Just (deleteFindMax x)
1003 #if __GLASGOW_HASKELL__ >= 700
1004 {-# INLINABLE maxViewWithKey #-}
1005 #endif
1006
1007 -- | /O(log n)/. Retrieves the value associated with minimal key of the
1008 -- map, and the map stripped of that element, or 'Nothing' if passed an
1009 -- empty map.
1010 --
1011 -- > minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a")
1012 -- > minView empty == Nothing
1013
1014 minView :: Map k a -> Maybe (a, Map k a)
1015 minView Tip = Nothing
1016 minView x = Just (first snd $ deleteFindMin x)
1017 #if __GLASGOW_HASKELL__ >= 700
1018 {-# INLINABLE minView #-}
1019 #endif
1020
1021 -- | /O(log n)/. Retrieves the value associated with maximal key of the
1022 -- map, and the map stripped of that element, or 'Nothing' if passed an
1023 --
1024 -- > maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b")
1025 -- > maxView empty == Nothing
1026
1027 maxView :: Map k a -> Maybe (a, Map k a)
1028 maxView Tip = Nothing
1029 maxView x = Just (first snd $ deleteFindMax x)
1030 #if __GLASGOW_HASKELL__ >= 700
1031 {-# INLINABLE maxView #-}
1032 #endif
1033
1034 -- Update the 1st component of a tuple (special case of Control.Arrow.first)
1035 first :: (a -> b) -> (a,c) -> (b,c)
1036 first f (x,y) = (f x, y)
1037
1038 {--------------------------------------------------------------------
1039 Union.
1040 --------------------------------------------------------------------}
1041 -- | The union of a list of maps:
1042 -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
1043 --
1044 -- > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
1045 -- > == fromList [(3, "b"), (5, "a"), (7, "C")]
1046 -- > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
1047 -- > == fromList [(3, "B3"), (5, "A3"), (7, "C")]
1048
1049 unions :: Ord k => [Map k a] -> Map k a
1050 unions ts
1051 = foldlStrict union empty ts
1052 #if __GLASGOW_HASKELL__ >= 700
1053 {-# INLINABLE unions #-}
1054 #endif
1055
1056 -- | The union of a list of maps, with a combining operation:
1057 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
1058 --
1059 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
1060 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
1061
1062 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
1063 unionsWith f ts
1064 = foldlStrict (unionWith f) empty ts
1065 #if __GLASGOW_HASKELL__ >= 700
1066 {-# INLINABLE unionsWith #-}
1067 #endif
1068
1069 -- | /O(n+m)/.
1070 -- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
1071 -- It prefers @t1@ when duplicate keys are encountered,
1072 -- i.e. (@'union' == 'unionWith' 'const'@).
1073 -- The implementation uses the efficient /hedge-union/ algorithm.
1074 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
1075 --
1076 -- > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]
1077
1078 union :: Ord k => Map k a -> Map k a -> Map k a
1079 union Tip t2 = t2
1080 union t1 Tip = t1
1081 union (Bin _ k x Tip Tip) t = insert k x t
1082 union t (Bin _ k x Tip Tip) = insertWith (\_ y->y) k x t
1083 union t1 t2 = hedgeUnionL NothingS NothingS t1 t2
1084 #if __GLASGOW_HASKELL__ >= 700
1085 {-# INLINABLE union #-}
1086 #endif
1087
1088 -- left-biased hedge union
1089 hedgeUnionL :: Ord a
1090 => MaybeS a -> MaybeS a -> Map a b -> Map a b
1091 -> Map a b
1092 hedgeUnionL _ _ t1 Tip
1093 = t1
1094 hedgeUnionL blo bhi Tip (Bin _ kx x l r)
1095 = join kx x (filterGt blo l) (filterLt bhi r)
1096 hedgeUnionL blo bhi (Bin _ kx x l r) t2
1097 = join kx x (hedgeUnionL blo bmi l (trim blo bmi t2))
1098 (hedgeUnionL bmi bhi r (trim bmi bhi t2))
1099 where
1100 bmi = JustS kx
1101 #if __GLASGOW_HASKELL__ >= 700
1102 {-# INLINABLE hedgeUnionL #-}
1103 #endif
1104
1105 {--------------------------------------------------------------------
1106 Union with a combining function
1107 --------------------------------------------------------------------}
1108 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
1109 --
1110 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
1111
1112 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
1113 unionWith f m1 m2
1114 = unionWithKey (\_ x y -> f x y) m1 m2
1115 {-# INLINE unionWith #-}
1116
1117 -- | /O(n+m)/.
1118 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
1119 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
1120 --
1121 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
1122 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
1123
1124 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
1125 unionWithKey _ Tip t2 = t2
1126 unionWithKey _ t1 Tip = t1
1127 unionWithKey f t1 t2 = hedgeUnionWithKey f NothingS NothingS t1 t2
1128 #if __GLASGOW_HASKELL__ >= 700
1129 {-# INLINABLE unionWithKey #-}
1130 #endif
1131
1132 hedgeUnionWithKey :: Ord a
1133 => (a -> b -> b -> b)
1134 -> MaybeS a -> MaybeS a
1135 -> Map a b -> Map a b
1136 -> Map a b
1137 hedgeUnionWithKey _ _ _ t1 Tip
1138 = t1
1139 hedgeUnionWithKey _ blo bhi Tip (Bin _ kx x l r)
1140 = join kx x (filterGt blo l) (filterLt bhi r)
1141 hedgeUnionWithKey f blo bhi (Bin _ kx x l r) t2
1142 = join kx newx (hedgeUnionWithKey f blo bmi l lt)
1143 (hedgeUnionWithKey f bmi bhi r gt)
1144 where
1145 bmi = JustS kx
1146 lt = trim blo bmi t2
1147 (found,gt) = trimLookupLo kx bhi t2
1148 newx = case found of
1149 Nothing -> x
1150 Just (_,y) -> f kx x y
1151 #if __GLASGOW_HASKELL__ >= 700
1152 {-# INLINABLE hedgeUnionWithKey #-}
1153 #endif
1154
1155 {--------------------------------------------------------------------
1156 Difference
1157 --------------------------------------------------------------------}
1158 -- | /O(n+m)/. Difference of two maps.
1159 -- Return elements of the first map not existing in the second map.
1160 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
1161 --
1162 -- > difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"
1163
1164 difference :: Ord k => Map k a -> Map k b -> Map k a
1165 difference Tip _ = Tip
1166 difference t1 Tip = t1
1167 difference t1 t2 = hedgeDiff NothingS NothingS t1 t2
1168 #if __GLASGOW_HASKELL__ >= 700
1169 {-# INLINABLE difference #-}
1170 #endif
1171
1172 hedgeDiff :: Ord a
1173 => MaybeS a -> MaybeS a -> Map a b -> Map a c
1174 -> Map a b
1175 hedgeDiff _ _ Tip _
1176 = Tip
1177 hedgeDiff blo bhi (Bin _ kx x l r) Tip
1178 = join kx x (filterGt blo l) (filterLt bhi r)
1179 hedgeDiff blo bhi t (Bin _ kx _ l r)
1180 = merge (hedgeDiff blo bmi (trim blo bmi t) l)
1181 (hedgeDiff bmi bhi (trim bmi bhi t) r)
1182 where
1183 bmi = JustS kx
1184 #if __GLASGOW_HASKELL__ >= 700
1185 {-# INLINABLE hedgeDiff #-}
1186 #endif
1187
1188 -- | /O(n+m)/. Difference with a combining function.
1189 -- When two equal keys are
1190 -- encountered, the combining function is applied to the values of these keys.
1191 -- If it returns 'Nothing', the element is discarded (proper set difference). If
1192 -- it returns (@'Just' y@), the element is updated with a new value @y@.
1193 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
1194 --
1195 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
1196 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
1197 -- > == singleton 3 "b:B"
1198
1199 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
1200 differenceWith f m1 m2
1201 = differenceWithKey (\_ x y -> f x y) m1 m2
1202 {-# INLINE differenceWith #-}
1203
1204 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
1205 -- encountered, the combining function is applied to the key and both values.
1206 -- If it returns 'Nothing', the element is discarded (proper set difference). If
1207 -- it returns (@'Just' y@), the element is updated with a new value @y@.
1208 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
1209 --
1210 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
1211 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
1212 -- > == singleton 3 "3:b|B"
1213
1214 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
1215 differenceWithKey _ Tip _ = Tip
1216 differenceWithKey _ t1 Tip = t1
1217 differenceWithKey f t1 t2 = hedgeDiffWithKey f NothingS NothingS t1 t2
1218 #if __GLASGOW_HASKELL__ >= 700
1219 {-# INLINABLE differenceWithKey #-}
1220 #endif
1221
1222 hedgeDiffWithKey :: Ord a
1223 => (a -> b -> c -> Maybe b)
1224 -> MaybeS a -> MaybeS a
1225 -> Map a b -> Map a c
1226 -> Map a b
1227 hedgeDiffWithKey _ _ _ Tip _
1228 = Tip
1229 hedgeDiffWithKey _ blo bhi (Bin _ kx x l r) Tip
1230 = join kx x (filterGt blo l) (filterLt bhi r)
1231 hedgeDiffWithKey f blo bhi t (Bin _ kx x l r)
1232 = case found of
1233 Nothing -> merge tl tr
1234 Just (ky,y) ->
1235 case f ky y x of
1236 Nothing -> merge tl tr
1237 Just z -> join ky z tl tr
1238 where
1239 bmi = JustS kx
1240 lt = trim blo bmi t
1241 (found,gt) = trimLookupLo kx bhi t
1242 tl = hedgeDiffWithKey f blo bmi lt l
1243 tr = hedgeDiffWithKey f bmi bhi gt r
1244 #if __GLASGOW_HASKELL__ >= 700
1245 {-# INLINABLE hedgeDiffWithKey #-}
1246 #endif
1247
1248
1249
1250 {--------------------------------------------------------------------
1251 Intersection
1252 --------------------------------------------------------------------}
1253 -- | /O(n+m)/. Intersection of two maps.
1254 -- Return data in the first map for the keys existing in both maps.
1255 -- (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
1256 --
1257 -- > intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"
1258
1259 intersection :: Ord k => Map k a -> Map k b -> Map k a
1260 intersection m1 m2
1261 = intersectionWithKey (\_ x _ -> x) m1 m2
1262 {-# INLINE intersection #-}
1263
1264 -- | /O(n+m)/. Intersection with a combining function.
1265 --
1266 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
1267
1268 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
1269 intersectionWith f m1 m2
1270 = intersectionWithKey (\_ x y -> f x y) m1 m2
1271 {-# INLINE intersectionWith #-}
1272
1273 -- | /O(n+m)/. Intersection with a combining function.
1274 -- Intersection is more efficient on (bigset \``intersection`\` smallset).
1275 --
1276 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
1277 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
1278
1279
1280 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
1281 intersectionWithKey _ Tip _ = Tip
1282 intersectionWithKey _ _ Tip = Tip
1283 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
1284 if s1 >= s2 then
1285 let (lt,found,gt) = splitLookupWithKey k2 t1
1286 tl = intersectionWithKey f lt l2
1287 tr = intersectionWithKey f gt r2
1288 in case found of
1289 Just (k,x) -> join k (f k x x2) tl tr
1290 Nothing -> merge tl tr
1291 else let (lt,found,gt) = splitLookup k1 t2
1292 tl = intersectionWithKey f l1 lt
1293 tr = intersectionWithKey f r1 gt
1294 in case found of
1295 Just x -> join k1 (f k1 x1 x) tl tr
1296 Nothing -> merge tl tr
1297 #if __GLASGOW_HASKELL__ >= 700
1298 {-# INLINABLE intersectionWithKey #-}
1299 #endif
1300
1301
1302
1303 {--------------------------------------------------------------------
1304 Submap
1305 --------------------------------------------------------------------}
1306 -- | /O(n+m)/.
1307 -- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
1308 --
1309 isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
1310 isSubmapOf m1 m2 = isSubmapOfBy (==) m1 m2
1311 #if __GLASGOW_HASKELL__ >= 700
1312 {-# INLINABLE isSubmapOf #-}
1313 #endif
1314
1315 {- | /O(n+m)/.
1316 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
1317 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
1318 applied to their respective values. For example, the following
1319 expressions are all 'True':
1320
1321 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1322 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1323 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
1324
1325 But the following are all 'False':
1326
1327 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
1328 > isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1329 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
1330
1331
1332 -}
1333 isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
1334 isSubmapOfBy f t1 t2
1335 = (size t1 <= size t2) && (submap' f t1 t2)
1336 #if __GLASGOW_HASKELL__ >= 700
1337 {-# INLINABLE isSubmapOfBy #-}
1338 #endif
1339
1340 submap' :: Ord a => (b -> c -> Bool) -> Map a b -> Map a c -> Bool
1341 submap' _ Tip _ = True
1342 submap' _ _ Tip = False
1343 submap' f (Bin _ kx x l r) t
1344 = case found of
1345 Nothing -> False
1346 Just y -> f x y && submap' f l lt && submap' f r gt
1347 where
1348 (lt,found,gt) = splitLookup kx t
1349 #if __GLASGOW_HASKELL__ >= 700
1350 {-# INLINABLE submap' #-}
1351 #endif
1352
1353 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
1354 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
1355 isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
1356 isProperSubmapOf m1 m2
1357 = isProperSubmapOfBy (==) m1 m2
1358 #if __GLASGOW_HASKELL__ >= 700
1359 {-# INLINABLE isProperSubmapOf #-}
1360 #endif
1361
1362 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
1363 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
1364 @m1@ and @m2@ are not equal,
1365 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
1366 applied to their respective values. For example, the following
1367 expressions are all 'True':
1368
1369 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
1370 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
1371
1372 But the following are all 'False':
1373
1374 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
1375 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
1376 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
1377
1378
1379 -}
1380 isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
1381 isProperSubmapOfBy f t1 t2
1382 = (size t1 < size t2) && (submap' f t1 t2)
1383 #if __GLASGOW_HASKELL__ >= 700
1384 {-# INLINABLE isProperSubmapOfBy #-}
1385 #endif
1386
1387 {--------------------------------------------------------------------
1388 Filter and partition
1389 --------------------------------------------------------------------}
1390 -- | /O(n)/. Filter all values that satisfy the predicate.
1391 --
1392 -- > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
1393 -- > filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
1394 -- > filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty
1395
1396 filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
1397 filter p m
1398 = filterWithKey (\_ x -> p x) m
1399 #if __GLASGOW_HASKELL__ >= 700
1400 {-# INLINABLE filter #-}
1401 #endif
1402
1403 -- | /O(n)/. Filter all keys\/values that satisfy the predicate.
1404 --
1405 -- > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
1406
1407 filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
1408 filterWithKey _ Tip = Tip
1409 filterWithKey p (Bin _ kx x l r)
1410 | p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
1411 | otherwise = merge (filterWithKey p l) (filterWithKey p r)
1412 #if __GLASGOW_HASKELL__ >= 700
1413 {-# INLINABLE filterWithKey #-}
1414 #endif
1415
1416 -- | /O(n)/. Partition the map according to a predicate. The first
1417 -- map contains all elements that satisfy the predicate, the second all
1418 -- elements that fail the predicate. See also 'split'.
1419 --
1420 -- > partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
1421 -- > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
1422 -- > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
1423
1424 partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
1425 partition p m
1426 = partitionWithKey (\_ x -> p x) m
1427 #if __GLASGOW_HASKELL__ >= 700
1428 {-# INLINABLE partition #-}
1429 #endif
1430
1431 -- | /O(n)/. Partition the map according to a predicate. The first
1432 -- map contains all elements that satisfy the predicate, the second all
1433 -- elements that fail the predicate. See also 'split'.
1434 --
1435 -- > partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
1436 -- > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
1437 -- > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
1438
1439 partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
1440 partitionWithKey _ Tip = (Tip,Tip)
1441 partitionWithKey p (Bin _ kx x l r)
1442 | p kx x = (join kx x l1 r1,merge l2 r2)
1443 | otherwise = (merge l1 r1,join kx x l2 r2)
1444 where
1445 (l1,l2) = partitionWithKey p l
1446 (r1,r2) = partitionWithKey p r
1447 #if __GLASGOW_HASKELL__ >= 700
1448 {-# INLINABLE partitionWithKey #-}
1449 #endif
1450
1451 -- | /O(n)/. Map values and collect the 'Just' results.
1452 --
1453 -- > let f x = if x == "a" then Just "new a" else Nothing
1454 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
1455
1456 mapMaybe :: Ord k => (a -> Maybe b) -> Map k a -> Map k b
1457 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
1458 #if __GLASGOW_HASKELL__ >= 700
1459 {-# INLINABLE mapMaybe #-}
1460 #endif
1461
1462 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
1463 --
1464 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
1465 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
1466
1467 mapMaybeWithKey :: Ord k => (k -> a -> Maybe b) -> Map k a -> Map k b
1468 mapMaybeWithKey _ Tip = Tip
1469 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
1470 Just y -> join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
1471 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
1472 #if __GLASGOW_HASKELL__ >= 700
1473 {-# INLINABLE mapMaybeWithKey #-}
1474 #endif
1475
1476 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
1477 --
1478 -- > let f a = if a < "c" then Left a else Right a
1479 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1480 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
1481 -- >
1482 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1483 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1484
1485 mapEither :: Ord k => (a -> Either b c) -> Map k a -> (Map k b, Map k c)
1486 mapEither f m
1487 = mapEitherWithKey (\_ x -> f x) m
1488 #if __GLASGOW_HASKELL__ >= 700
1489 {-# INLINABLE mapEither #-}
1490 #endif
1491
1492 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
1493 --
1494 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
1495 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1496 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
1497 -- >
1498 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1499 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
1500
1501 mapEitherWithKey :: Ord k =>
1502 (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
1503 mapEitherWithKey _ Tip = (Tip, Tip)
1504 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
1505 Left y -> (join kx y l1 r1, merge l2 r2)
1506 Right z -> (merge l1 r1, join kx z l2 r2)
1507 where
1508 (l1,l2) = mapEitherWithKey f l
1509 (r1,r2) = mapEitherWithKey f r
1510 #if __GLASGOW_HASKELL__ >= 700
1511 {-# INLINABLE mapEitherWithKey #-}
1512 #endif
1513
1514 {--------------------------------------------------------------------
1515 Mapping
1516 --------------------------------------------------------------------}
1517 -- | /O(n)/. Map a function over all values in the map.
1518 --
1519 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
1520
1521 map :: (a -> b) -> Map k a -> Map k b
1522 map f = mapWithKey (\_ x -> f x)
1523 #if __GLASGOW_HASKELL__ >= 700
1524 {-# INLINABLE map #-}
1525 #endif
1526
1527 -- | /O(n)/. Map a function over all values in the map.
1528 --
1529 -- > let f key x = (show key) ++ ":" ++ x
1530 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
1531
1532 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
1533 mapWithKey _ Tip = Tip
1534 mapWithKey f (Bin sx kx x l r) = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
1535 #if __GLASGOW_HASKELL__ >= 700
1536 {-# INLINABLE mapWithKey #-}
1537 #endif
1538
1539 -- | /O(n)/. The function 'mapAccum' threads an accumulating
1540 -- argument through the map in ascending order of keys.
1541 --
1542 -- > let f a b = (a ++ b, b ++ "X")
1543 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
1544
1545 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1546 mapAccum f a m
1547 = mapAccumWithKey (\a' _ x' -> f a' x') a m
1548 #if __GLASGOW_HASKELL__ >= 700
1549 {-# INLINABLE mapAccum #-}
1550 #endif
1551
1552 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1553 -- argument through the map in ascending order of keys.
1554 --
1555 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1556 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1557
1558 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1559 mapAccumWithKey f a t
1560 = mapAccumL f a t
1561 #if __GLASGOW_HASKELL__ >= 700
1562 {-# INLINABLE mapAccumWithKey #-}
1563 #endif
1564
1565 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
1566 -- argument through the map in ascending order of keys.
1567 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1568 mapAccumL _ a Tip = (a,Tip)
1569 mapAccumL f a (Bin sx kx x l r) =
1570 let (a1,l') = mapAccumL f a l
1571 (a2,x') = f a1 kx x
1572 (a3,r') = mapAccumL f a2 r
1573 in (a3,Bin sx kx x' l' r')
1574 #if __GLASGOW_HASKELL__ >= 700
1575 {-# INLINABLE mapAccumL #-}
1576 #endif
1577
1578 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1579 -- argument through the map in descending order of keys.
1580 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1581 mapAccumRWithKey _ a Tip = (a,Tip)
1582 mapAccumRWithKey f a (Bin sx kx x l r) =
1583 let (a1,r') = mapAccumRWithKey f a r
1584 (a2,x') = f a1 kx x
1585 (a3,l') = mapAccumRWithKey f a2 l
1586 in (a3,Bin sx kx x' l' r')
1587 #if __GLASGOW_HASKELL__ >= 700
1588 {-# INLINABLE mapAccumRWithKey #-}
1589 #endif
1590
1591 -- | /O(n*log n)/.
1592 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
1593 --
1594 -- The size of the result may be smaller if @f@ maps two or more distinct
1595 -- keys to the same new key. In this case the value at the smallest of
1596 -- these keys is retained.
1597 --
1598 -- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
1599 -- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
1600 -- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
1601
1602 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
1603 mapKeys = mapKeysWith (\x _ -> x)
1604 #if __GLASGOW_HASKELL__ >= 700
1605 {-# INLINABLE mapKeys #-}
1606 #endif
1607
1608 -- | /O(n*log n)/.
1609 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1610 --
1611 -- The size of the result may be smaller if @f@ maps two or more distinct
1612 -- keys to the same new key. In this case the associated values will be
1613 -- combined using @c@.
1614 --
1615 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1616 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1617
1618 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1619 mapKeysWith c f = fromListWith c . List.map fFirst . toList
1620 where fFirst (x,y) = (f x, y)
1621 #if __GLASGOW_HASKELL__ >= 700
1622 {-# INLINABLE mapKeysWith #-}
1623 #endif
1624
1625
1626 -- | /O(n)/.
1627 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
1628 -- is strictly monotonic.
1629 -- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
1630 -- /The precondition is not checked./
1631 -- Semi-formally, we have:
1632 --
1633 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
1634 -- > ==> mapKeysMonotonic f s == mapKeys f s
1635 -- > where ls = keys s
1636 --
1637 -- This means that @f@ maps distinct original keys to distinct resulting keys.
1638 -- This function has better performance than 'mapKeys'.
1639 --
1640 -- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
1641 -- > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
1642 -- > valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == False
1643
1644 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
1645 mapKeysMonotonic _ Tip = Tip
1646 mapKeysMonotonic f (Bin sz k x l r) =
1647 Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
1648 #if __GLASGOW_HASKELL__ >= 700
1649 {-# INLINABLE mapKeysMonotonic #-}
1650 #endif
1651
1652 {--------------------------------------------------------------------
1653 Folds
1654 --------------------------------------------------------------------}
1655
1656 -- | /O(n)/. Fold the values in the map using the given right-associative
1657 -- binary operator. This function is an equivalent of 'foldr' and is present
1658 -- for compatibility only.
1659 --
1660 -- /Please note that fold will be deprecated in the future and removed./
1661 fold :: (a -> b -> b) -> b -> Map k a -> b
1662 fold = foldr
1663 {-# INLINE fold #-}
1664
1665 -- | /O(n)/. Fold the values in the map using the given right-associative
1666 -- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'elems'@.
1667 --
1668 -- For example,
1669 --
1670 -- > elems map = foldr (:) [] map
1671 --
1672 -- > let f a len = len + (length a)
1673 -- > foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
1674 foldr :: (a -> b -> b) -> b -> Map k a -> b
1675 foldr f = go
1676 where
1677 go z Tip = z
1678 go z (Bin _ _ x l r) = go (f x (go z r)) l
1679 {-# INLINE foldr #-}
1680
1681 -- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
1682 -- evaluated before using the result in the next application. This
1683 -- function is strict in the starting value.
1684 foldr' :: (a -> b -> b) -> b -> Map k a -> b
1685 foldr' f = go
1686 where
1687 STRICT_1_OF_2(go)
1688 go z Tip = z
1689 go z (Bin _ _ x l r) = go (f x (go z r)) l
1690 {-# INLINE foldr' #-}
1691
1692 -- | /O(n)/. Fold the values in the map using the given left-associative
1693 -- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'elems'@.
1694 --
1695 -- For example,
1696 --
1697 -- > elems = reverse . foldl (flip (:)) []
1698 --
1699 -- > let f len a = len + (length a)
1700 -- > foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
1701 foldl :: (a -> b -> a) -> a -> Map k b -> a
1702 foldl f = go
1703 where
1704 go z Tip = z
1705 go z (Bin _ _ x l r) = go (f (go z l) x) r
1706 {-# INLINE foldl #-}
1707
1708 -- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
1709 -- evaluated before using the result in the next application. This
1710 -- function is strict in the starting value.
1711 foldl' :: (a -> b -> a) -> a -> Map k b -> a
1712 foldl' f = go
1713 where
1714 STRICT_1_OF_2(go)
1715 go z Tip = z
1716 go z (Bin _ _ x l r) = go (f (go z l) x) r
1717 {-# INLINE foldl' #-}
1718
1719 -- | /O(n)/. Fold the keys and values in the map using the given right-associative
1720 -- binary operator. This function is an equivalent of 'foldrWithKey' and is present
1721 -- for compatibility only.
1722 --
1723 -- /Please note that foldWithKey will be deprecated in the future and removed./
1724 foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
1725 foldWithKey = foldrWithKey
1726 {-# INLINE foldWithKey #-}
1727
1728 -- | /O(n)/. Fold the keys and values in the map using the given right-associative
1729 -- binary operator, such that
1730 -- @'foldrWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
1731 --
1732 -- For example,
1733 --
1734 -- > keys map = foldrWithKey (\k x ks -> k:ks) [] map
1735 --
1736 -- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
1737 -- > foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
1738 foldrWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
1739 foldrWithKey f = go
1740 where
1741 go z Tip = z
1742 go z (Bin _ kx x l r) = go (f kx x (go z r)) l
1743 {-# INLINE foldrWithKey #-}
1744
1745 -- | /O(n)/. A strict version of 'foldrWithKey'. Each application of the operator is
1746 -- evaluated before using the result in the next application. This
1747 -- function is strict in the starting value.
1748 foldrWithKey' :: (k -> a -> b -> b) -> b -> Map k a -> b
1749 foldrWithKey' f = go
1750 where
1751 STRICT_1_OF_2(go)
1752 go z Tip = z
1753 go z (Bin _ kx x l r) = go (f kx x (go z r)) l
1754 {-# INLINE foldrWithKey' #-}
1755
1756 -- | /O(n)/. Fold the keys and values in the map using the given left-associative
1757 -- binary operator, such that
1758 -- @'foldlWithKey' f z == 'Prelude.foldl' (\\z' (kx, x) -> f z' kx x) z . 'toAscList'@.
1759 --
1760 -- For example,
1761 --
1762 -- > keys = reverse . foldlWithKey (\ks k x -> k:ks) []
1763 --
1764 -- > let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
1765 -- > foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)"
1766 foldlWithKey :: (a -> k -> b -> a) -> a -> Map k b -> a
1767 foldlWithKey f = go
1768 where
1769 go z Tip = z
1770 go z (Bin _ kx x l r) = go (f (go z l) kx x) r
1771 {-# INLINE foldlWithKey #-}
1772
1773 -- | /O(n)/. A strict version of 'foldlWithKey'. Each application of the operator is
1774 -- evaluated before using the result in the next application. This
1775 -- function is strict in the starting value.
1776 foldlWithKey' :: (a -> k -> b -> a) -> a -> Map k b -> a
1777 foldlWithKey' f = go
1778 where
1779 STRICT_1_OF_2(go)
1780 go z Tip = z
1781 go z (Bin _ kx x l r) = go (f (go z l) kx x) r
1782 {-# INLINE foldlWithKey' #-}
1783
1784 {--------------------------------------------------------------------
1785 List variations
1786 --------------------------------------------------------------------}
1787 -- | /O(n)/.
1788 -- Return all elements of the map in the ascending order of their keys.
1789 --
1790 -- > elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
1791 -- > elems empty == []
1792
1793 elems :: Map k a -> [a]
1794 elems m
1795 = [x | (_,x) <- assocs m]
1796 #if __GLASGOW_HASKELL__ >= 700
1797 {-# INLINABLE elems #-}
1798 #endif
1799
1800 -- | /O(n)/. Return all keys of the map in ascending order.
1801 --
1802 -- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
1803 -- > keys empty == []
1804
1805 keys :: Map k a -> [k]
1806 keys m
1807 = [k | (k,_) <- assocs m]
1808 #if __GLASGOW_HASKELL__ >= 700
1809 {-# INLINABLE keys #-}
1810 #endif
1811
1812 -- | /O(n)/. The set of all keys of the map.
1813 --
1814 -- > keysSet (fromList [(5,"a"), (3,"b")]) == Data.Set.fromList [3,5]
1815 -- > keysSet empty == Data.Set.empty
1816
1817 keysSet :: Map k a -> Set.Set k
1818 keysSet m = Set.fromDistinctAscList (keys m)
1819 #if __GLASGOW_HASKELL__ >= 700
1820 {-# INLINABLE keysSet #-}
1821 #endif
1822
1823 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
1824 --
1825 -- > assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1826 -- > assocs empty == []
1827
1828 assocs :: Map k a -> [(k,a)]
1829 assocs m
1830 = toList m
1831 #if __GLASGOW_HASKELL__ >= 700
1832 {-# INLINABLE assocs #-}
1833 #endif
1834
1835 {--------------------------------------------------------------------
1836 Lists
1837 use [foldlStrict] to reduce demand on the control-stack
1838 --------------------------------------------------------------------}
1839 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1840 -- If the list contains more than one value for the same key, the last value
1841 -- for the key is retained.
1842 --
1843 -- > fromList [] == empty
1844 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1845 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1846
1847 fromList :: Ord k => [(k,a)] -> Map k a
1848 fromList xs
1849 = foldlStrict ins empty xs
1850 where
1851 ins t (k,x) = insert k x t
1852 #if __GLASGOW_HASKELL__ >= 700
1853 {-# INLINABLE fromList #-}
1854 #endif
1855
1856 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1857 --
1858 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1859 -- > fromListWith (++) [] == empty
1860
1861 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1862 fromListWith f xs
1863 = fromListWithKey (\_ x y -> f x y) xs
1864 #if __GLASGOW_HASKELL__ >= 700
1865 {-# INLINABLE fromListWith #-}
1866 #endif
1867
1868 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1869 --
1870 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1871 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1872 -- > fromListWithKey f [] == empty
1873
1874 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1875 fromListWithKey f xs
1876 = foldlStrict ins empty xs
1877 where
1878 ins t (k,x) = insertWithKey f k x t
1879 #if __GLASGOW_HASKELL__ >= 700
1880 {-# INLINABLE fromListWithKey #-}
1881 #endif
1882
1883 -- | /O(n)/. Convert to a list of key\/value pairs.
1884 --
1885 -- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1886 -- > toList empty == []
1887
1888 toList :: Map k a -> [(k,a)]
1889 toList t = toAscList t
1890 #if __GLASGOW_HASKELL__ >= 700
1891 {-# INLINABLE toList #-}
1892 #endif
1893
1894 -- | /O(n)/. Convert to an ascending list.
1895 --
1896 -- > toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1897
1898 toAscList :: Map k a -> [(k,a)]
1899 toAscList t = foldrWithKey (\k x xs -> (k,x):xs) [] t
1900 #if __GLASGOW_HASKELL__ >= 700
1901 {-# INLINABLE toAscList #-}
1902 #endif
1903
1904 -- | /O(n)/. Convert to a descending list.
1905 toDescList :: Map k a -> [(k,a)]
1906 toDescList t = foldlWithKey (\xs k x -> (k,x):xs) [] t
1907 #if __GLASGOW_HASKELL__ >= 700
1908 {-# INLINABLE toDescList #-}
1909 #endif
1910
1911 {--------------------------------------------------------------------
1912 Building trees from ascending/descending lists can be done in linear time.
1913
1914 Note that if [xs] is ascending that:
1915 fromAscList xs == fromList xs
1916 fromAscListWith f xs == fromListWith f xs
1917 --------------------------------------------------------------------}
1918 -- | /O(n)/. Build a map from an ascending list in linear time.
1919 -- /The precondition (input list is ascending) is not checked./
1920 --
1921 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1922 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1923 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1924 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1925
1926 fromAscList :: Eq k => [(k,a)] -> Map k a
1927 fromAscList xs
1928 = fromAscListWithKey (\_ x _ -> x) xs
1929 #if __GLASGOW_HASKELL__ >= 700
1930 {-# INLINABLE fromAscList #-}
1931 #endif
1932
1933 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1934 -- /The precondition (input list is ascending) is not checked./
1935 --
1936 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1937 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1938 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1939
1940 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1941 fromAscListWith f xs
1942 = fromAscListWithKey (\_ x y -> f x y) xs
1943 #if __GLASGOW_HASKELL__ >= 700
1944 {-# INLINABLE fromAscListWith #-}
1945 #endif
1946
1947 -- | /O(n)/. Build a map from an ascending list in linear time with a
1948 -- combining function for equal keys.
1949 -- /The precondition (input list is ascending) is not checked./
1950 --
1951 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1952 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1953 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1954 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1955
1956 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1957 fromAscListWithKey f xs
1958 = fromDistinctAscList (combineEq f xs)
1959 where
1960 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1961 combineEq _ xs'
1962 = case xs' of
1963 [] -> []
1964 [x] -> [x]
1965 (x:xx) -> combineEq' x xx
1966
1967 combineEq' z [] = [z]
1968 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1969 | kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs'
1970 | otherwise = z:combineEq' x xs'
1971 #if __GLASGOW_HASKELL__ >= 700
1972 {-# INLINABLE fromAscListWithKey #-}
1973 #endif
1974
1975
1976 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1977 -- /The precondition is not checked./
1978 --
1979 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1980 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1981 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1982
1983 fromDistinctAscList :: [(k,a)] -> Map k a
1984 fromDistinctAscList xs
1985 = build const (length xs) xs
1986 where
1987 -- 1) use continuations so that we use heap space instead of stack space.
1988 -- 2) special case for n==5 to build bushier trees.
1989 build c 0 xs' = c Tip xs'
1990 build c 5 xs' = case xs' of
1991 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1992 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1993 _ -> error "fromDistinctAscList build"
1994 build c n xs' = seq nr $ build (buildR nr c) nl xs'
1995 where
1996 nl = n `div` 2
1997 nr = n - nl - 1
1998
1999 buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
2000 buildR _ _ _ [] = error "fromDistinctAscList buildR []"
2001 buildB l k x c r zs = c (bin k x l r) zs
2002 #if __GLASGOW_HASKELL__ >= 700
2003 {-# INLINABLE fromDistinctAscList #-}
2004 #endif
2005
2006
2007 {--------------------------------------------------------------------
2008 Utility functions that return sub-ranges of the original
2009 tree. Some functions take a `Maybe value` as an argument to
2010 allow comparisons against infinite values. These are called `blow`
2011 (Nothing is -\infty) and `bhigh` (here Nothing is +\infty).
2012 We use MaybeS value, which is a Maybe strict in the Just case.
2013
2014 [trim blow bhigh t] A tree that is either empty or where [x > blow]
2015 and [x < bhigh] for the value [x] of the root.
2016 [filterGt blow t] A tree where for all values [k]. [k > blow]
2017 [filterLt bhigh t] A tree where for all values [k]. [k < bhigh]
2018
2019 [split k t] Returns two trees [l] and [r] where all keys
2020 in [l] are <[k] and all keys in [r] are >[k].
2021 [splitLookup k t] Just like [split] but also returns whether [k]
2022 was found in the tree.
2023 --------------------------------------------------------------------}
2024
2025 data MaybeS a = NothingS | JustS !a
2026
2027 {--------------------------------------------------------------------
2028 [trim blo bhi t] trims away all subtrees that surely contain no
2029 values between the range [blo] to [bhi]. The returned tree is either
2030 empty or the key of the root is between @blo@ and @bhi@.
2031 --------------------------------------------------------------------}
2032 trim :: Ord k => MaybeS k -> MaybeS k -> Map k a -> Map k a
2033 trim NothingS NothingS t = t
2034 trim (JustS lk) NothingS t = greater lk t where greater lo (Bin _ k _ _ r) | k <= lo = greater lo r
2035 greater _ t' = t'
2036 trim NothingS (JustS hk) t = lesser hk t where lesser hi (Bin _ k _ l _) | k >= hi = lesser hi l
2037 lesser _ t' = t'
2038 trim (JustS lk) (JustS hk) t = middle lk hk t where middle lo hi (Bin _ k _ _ r) | k <= lo = middle lo hi r
2039 middle lo hi (Bin _ k _ l _) | k >= hi = middle lo hi l
2040 middle _ _ t' = t'
2041 #if __GLASGOW_HASKELL__ >= 700
2042 {-# INLINABLE trim #-}
2043 #endif
2044
2045 trimLookupLo :: Ord k => k -> MaybeS k -> Map k a -> (Maybe (k,a), Map k a)
2046 trimLookupLo _ _ Tip = (Nothing, Tip)
2047 trimLookupLo lo hi t@(Bin _ kx x l r)
2048 = case compare lo kx of
2049 LT -> case compare' kx hi of
2050 LT -> (lookupAssoc lo t, t)
2051 _ -> trimLookupLo lo hi l
2052 GT -> trimLookupLo lo hi r
2053 EQ -> (Just (kx,x),trim (JustS lo) hi r)
2054 where compare' _ NothingS = LT
2055 compare' kx' (JustS hi') = compare kx' hi'
2056 #if __GLASGOW_HASKELL__ >= 700
2057 {-# INLINABLE trimLookupLo #-}
2058 #endif
2059
2060
2061 {--------------------------------------------------------------------
2062 [filterGt b t] filter all keys >[b] from tree [t]
2063 [filterLt b t] filter all keys <[b] from tree [t]
2064 --------------------------------------------------------------------}
2065 filterGt :: Ord k => MaybeS k -> Map k v -> Map k v
2066 filterGt NothingS t = t
2067 filterGt (JustS b) t = filter' b t
2068 where filter' _ Tip = Tip
2069 filter' b' (Bin _ kx x l r) =
2070 case compare b' kx of LT -> join kx x (filter' b' l) r
2071 EQ -> r
2072 GT -> filter' b' r
2073 #if __GLASGOW_HASKELL__ >= 700
2074 {-# INLINABLE filterGt #-}
2075 #endif
2076
2077 filterLt :: Ord k => MaybeS k -> Map k v -> Map k v
2078 filterLt NothingS t = t
2079 filterLt (JustS b) t = filter' b t
2080 where filter' _ Tip = Tip
2081 filter' b' (Bin _ kx x l r) =
2082 case compare kx b' of LT -> join kx x l (filter' b' r)
2083 EQ -> l
2084 GT -> filter' b' l
2085 #if __GLASGOW_HASKELL__ >= 700
2086 {-# INLINABLE filterLt #-}
2087 #endif
2088
2089 {--------------------------------------------------------------------
2090 Split
2091 --------------------------------------------------------------------}
2092 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
2093 -- the keys in @map1@ are smaller than @k@ and the keys in @map2@ larger than @k@.
2094 -- Any key equal to @k@ is found in neither @map1@ nor @map2@.
2095 --
2096 -- > split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")])
2097 -- > split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a")
2098 -- > split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
2099 -- > split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty)
2100 -- > split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty)
2101
2102 split :: Ord k => k -> Map k a -> (Map k a,Map k a)
2103 split k t = k `seq`
2104 case t of
2105 Tip -> (Tip, Tip)
2106 Bin _ kx x l r -> case compare k kx of
2107 LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
2108 GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
2109 EQ -> (l,r)
2110 #if __GLASGOW_HASKELL__ >= 700
2111 {-# INLINABLE split #-}
2112 #endif
2113
2114 -- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
2115 -- like 'split' but also returns @'lookup' k map@.
2116 --
2117 -- > splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")])
2118 -- > splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a")
2119 -- > splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a")
2120 -- > splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty)
2121 -- > splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)
2122
2123 splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
2124 splitLookup k t = k `seq`
2125 case t of
2126 Tip -> (Tip,Nothing,Tip)
2127 Bin _ kx x l r -> case compare k kx of
2128 LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
2129 GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
2130 EQ -> (l,Just x,r)
2131 #if __GLASGOW_HASKELL__ >= 700
2132 {-# INLINABLE splitLookup #-}
2133 #endif
2134
2135 -- | /O(log n)/.
2136 splitLookupWithKey :: Ord k => k -> Map k a -> (Map k a,Maybe (k,a),Map k a)
2137 splitLookupWithKey k t = k `seq`
2138 case t of
2139 Tip -> (Tip,Nothing,Tip)
2140 Bin _ kx x l r -> case compare k kx of
2141 LT -> let (lt,z,gt) = splitLookupWithKey k l in (lt,z,join kx x gt r)
2142 GT -> let (lt,z,gt) = splitLookupWithKey k r in (join kx x l lt,z,gt)
2143 EQ -> (l,Just (kx, x),r)
2144 #if __GLASGOW_HASKELL__ >= 700
2145 {-# INLINABLE splitLookupWithKey #-}
2146 #endif
2147
2148 {--------------------------------------------------------------------
2149 Utility functions that maintain the balance properties of the tree.
2150 All constructors assume that all values in [l] < [k] and all values
2151 in [r] > [k], and that [l] and [r] are valid trees.
2152
2153 In order of sophistication:
2154 [Bin sz k x l r] The type constructor.
2155 [bin k x l r] Maintains the correct size, assumes that both [l]
2156 and [r] are balanced with respect to each other.
2157 [balance k x l r] Restores the balance and size.
2158 Assumes that the original tree was balanced and
2159 that [l] or [r] has changed by at most one element.
2160 [join k x l r] Restores balance and size.
2161
2162 Furthermore, we can construct a new tree from two trees. Both operations
2163 assume that all values in [l] < all values in [r] and that [l] and [r]
2164 are valid:
2165 [glue l r] Glues [l] and [r] together. Assumes that [l] and
2166 [r] are already balanced with respect to each other.
2167 [merge l r] Merges two trees and restores balance.
2168
2169 Note: in contrast to Adam's paper, we use (<=) comparisons instead
2170 of (<) comparisons in [join], [merge] and [balance].
2171 Quickcheck (on [difference]) showed that this was necessary in order
2172 to maintain the invariants. It is quite unsatisfactory that I haven't
2173 been able to find out why this is actually the case! Fortunately, it
2174 doesn't hurt to be a bit more conservative.
2175 --------------------------------------------------------------------}
2176
2177 {--------------------------------------------------------------------
2178 Join
2179 --------------------------------------------------------------------}
2180 join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
2181 join kx x Tip r = insertMin kx x r
2182 join kx x l Tip = insertMax kx x l
2183 join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
2184 | delta*sizeL < sizeR = balanceL kz z (join kx x l lz) rz
2185 | delta*sizeR < sizeL = balanceR ky y ly (join kx x ry r)
2186 | otherwise = bin kx x l r
2187 #if __GLASGOW_HASKELL__ >= 700
2188 {-# INLINABLE join #-}
2189 #endif
2190
2191
2192 -- insertMin and insertMax don't perform potentially expensive comparisons.
2193 insertMax,insertMin :: k -> a -> Map k a -> Map k a
2194 insertMax kx x t
2195 = case t of
2196 Tip -> singleton kx x
2197 Bin _ ky y l r
2198 -> balanceR ky y l (insertMax kx x r)
2199 #if __GLASGOW_HASKELL__ >= 700
2200 {-# INLINABLE insertMax #-}
2201 #endif
2202
2203 insertMin kx x t
2204 = case t of
2205 Tip -> singleton kx x
2206 Bin _ ky y l r
2207 -> balanceL ky y (insertMin kx x l) r
2208 #if __GLASGOW_HASKELL__ >= 700
2209 {-# INLINABLE insertMin #-}
2210 #endif
2211
2212 {--------------------------------------------------------------------
2213 [merge l r]: merges two trees.
2214 --------------------------------------------------------------------}
2215 merge :: Map k a -> Map k a -> Map k a
2216 merge Tip r = r
2217 merge l Tip = l
2218 merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
2219 | delta*sizeL < sizeR = balanceL ky y (merge l ly) ry
2220 | delta*sizeR < sizeL = balanceR kx x lx (merge rx r)
2221 | otherwise = glue l r
2222 #if __GLASGOW_HASKELL__ >= 700
2223 {-# INLINABLE merge #-}
2224 #endif
2225
2226 {--------------------------------------------------------------------
2227 [glue l r]: glues two trees together.
2228 Assumes that [l] and [r] are already balanced with respect to each other.
2229 --------------------------------------------------------------------}
2230 glue :: Map k a -> Map k a -> Map k a
2231 glue Tip r = r
2232 glue l Tip = l
2233 glue l r
2234 | size l > size r = let ((km,m),l') = deleteFindMax l in balanceR km m l' r
2235 | otherwise = let ((km,m),r') = deleteFindMin r in balanceL km m l r'
2236 #if __GLASGOW_HASKELL__ >= 700
2237 {-# INLINABLE glue #-}
2238 #endif
2239
2240
2241 -- | /O(log n)/. Delete and find the minimal element.
2242 --
2243 -- > deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")])
2244 -- > deleteFindMin Error: can not return the minimal element of an empty map
2245
2246 deleteFindMin :: Map k a -> ((k,a),Map k a)
2247 deleteFindMin t
2248 = case t of
2249 Bin _ k x Tip r -> ((k,x),r)
2250 Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balanceR k x l' r)
2251 Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
2252 #if __GLASGOW_HASKELL__ >= 700
2253 {-# INLINABLE deleteFindMin #-}
2254 #endif
2255
2256 -- | /O(log n)/. Delete and find the maximal element.
2257 --
2258 -- > deleteFindMax (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((10,"c"), fromList [(3,"b"), (5,"a")])
2259 -- > deleteFindMax empty Error: can not return the maximal element of an empty map
2260
2261 deleteFindMax :: Map k a -> ((k,a),Map k a)
2262 deleteFindMax t
2263 = case t of
2264 Bin _ k x l Tip -> ((k,x),l)
2265 Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balanceL k x l r')
2266 Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
2267 #if __GLASGOW_HASKELL__ >= 700
2268 {-# INLINABLE deleteFindMax #-}
2269 #endif
2270
2271
2272 {--------------------------------------------------------------------
2273 [balance l x r] balances two trees with value x.
2274 The sizes of the trees should balance after decreasing the
2275 size of one of them. (a rotation).
2276
2277 [delta] is the maximal relative difference between the sizes of
2278 two trees, it corresponds with the [w] in Adams' paper.
2279 [ratio] is the ratio between an outer and inner sibling of the
2280 heavier subtree in an unbalanced setting. It determines
2281 whether a double or single rotation should be performed
2282 to restore balance. It is corresponds with the inverse
2283 of $\alpha$ in Adam's article.
2284
2285 Note that according to the Adam's paper:
2286 - [delta] should be larger than 4.646 with a [ratio] of 2.
2287 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
2288
2289 But the Adam's paper is erroneous:
2290 - It can be proved that for delta=2 and delta>=5 there does
2291 not exist any ratio that would work.
2292 - Delta=4.5 and ratio=2 does not work.
2293
2294 That leaves two reasonable variants, delta=3 and delta=4,
2295 both with ratio=2.
2296
2297 - A lower [delta] leads to a more 'perfectly' balanced tree.
2298 - A higher [delta] performs less rebalancing.
2299
2300 In the benchmarks, delta=3 is faster on insert operations,
2301 and delta=4 has slightly better deletes. As the insert speedup
2302 is larger, we currently use delta=3.
2303
2304 --------------------------------------------------------------------}
2305 delta,ratio :: Int
2306 delta = 3
2307 ratio = 2
2308
2309 -- The balance function is equivalent to the following:
2310 --
2311 -- balance :: k -> a -> Map k a -> Map k a -> Map k a
2312 -- balance k x l r
2313 -- | sizeL + sizeR <= 1 = Bin sizeX k x l r
2314 -- | sizeR > delta*sizeL = rotateL k x l r
2315 -- | sizeL > delta*sizeR = rotateR k x l r
2316 -- | otherwise = Bin sizeX k x l r
2317 -- where
2318 -- sizeL = size l
2319 -- sizeR = size r
2320 -- sizeX = sizeL + sizeR + 1
2321 --
2322 -- rotateL :: a -> b -> Map a b -> Map a b -> Map a b
2323 -- rotateL k x l r@(Bin _ _ _ ly ry) | size ly < ratio*size ry = singleL k x l r
2324 -- | otherwise = doubleL k x l r
2325 --
2326 -- rotateR :: a -> b -> Map a b -> Map a b -> Map a b
2327 -- rotateR k x l@(Bin _ _ _ ly ry) r | size ry < ratio*size ly = singleR k x l r
2328 -- | otherwise = doubleR k x l r
2329 --
2330 -- singleL, singleR :: a -> b -> Map a b -> Map a b -> Map a b
2331 -- singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
2332 -- singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
2333 --
2334 -- doubleL, doubleR :: a -> b -> Map a b -> Map a b -> Map a b
2335 -- doubleL k1 x1 t1 (Bin _ k2 x2 (Bin _ k3 x3 t2 t3) t4) = bin k3 x3 (bin k1 x1 t1 t2) (bin k2 x2 t3 t4)
2336 -- doubleR k1 x1 (Bin _ k2 x2 t1 (Bin _ k3 x3 t2 t3)) t4 = bin k3 x3 (bin k2 x2 t1 t2) (bin k1 x1 t3 t4)
2337 --
2338 -- It is only written in such a way that every node is pattern-matched only once.
2339
2340 balance :: k -> a -> Map k a -> Map k a -> Map k a
2341 balance k x l r = case l of
2342 Tip -> case r of
2343 Tip -> Bin 1 k x Tip Tip
2344 (Bin _ _ _ Tip Tip) -> Bin 2 k x Tip r
2345 (Bin _ rk rx Tip rr@(Bin _ _ _ _ _)) -> Bin 3 rk rx (Bin 1 k x Tip Tip) rr
2346 (Bin _ rk rx (Bin _ rlk rlx _ _) Tip) -> Bin 3 rlk rlx (Bin 1 k x Tip Tip) (Bin 1 rk rx Tip Tip)
2347 (Bin rs rk rx rl@(Bin rls rlk rlx rll rlr) rr@(Bin rrs _ _ _ _))
2348 | rls < ratio*rrs -> Bin (1+rs) rk rx (Bin (1+rls) k x Tip rl) rr
2349 | otherwise -> Bin (1+rs) rlk rlx (Bin (1+size rll) k x Tip rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
2350
2351 (Bin ls lk lx ll lr) -> case r of
2352 Tip -> case (ll, lr) of
2353 (Tip, Tip) -> Bin 2 k x l Tip
2354 (Tip, (Bin _ lrk lrx _ _)) -> Bin 3 lrk lrx (Bin 1 lk lx Tip Tip) (Bin 1 k x Tip Tip)
2355 ((Bin _ _ _ _ _), Tip) -> Bin 3 lk lx ll (Bin 1 k x Tip Tip)
2356 ((Bin lls _ _ _ _), (Bin lrs lrk lrx lrl lrr))
2357 | lrs < ratio*lls -> Bin (1+ls) lk lx ll (Bin (1+lrs) k x lr Tip)
2358 | otherwise -> Bin (1+ls) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+size lrr) k x lrr Tip)
2359 (Bin rs rk rx rl rr)
2360 | rs > delta*ls -> case (rl, rr) of
2361 (Bin rls rlk rlx rll rlr, Bin rrs _ _ _ _)
2362 | rls < ratio*rrs -> Bin (1+ls+rs) rk rx (Bin (1+ls+rls) k x l rl) rr
2363 | otherwise -> Bin (1+ls+rs) rlk rlx (Bin (1+ls+size rll) k x l rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
2364 (_, _) -> error "Failure in Data.Map.balance"
2365 | ls > delta*rs -> case (ll, lr) of
2366 (Bin lls _ _ _ _, Bin lrs lrk lrx lrl lrr)
2367 | lrs < ratio*lls -> Bin (1+ls+rs) lk lx ll (Bin (1+rs+lrs) k x lr r)
2368 | otherwise -> Bin (1+ls+rs) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+rs+size lrr) k x lrr r)
2369 (_, _) -> error "Failure in Data.Map.balance"
2370 | otherwise -> Bin (1+ls+rs) k x l r
2371 {-# NOINLINE balance #-}
2372
2373 -- Functions balanceL and balanceR are specialised versions of balance.
2374 -- balanceL only checks whether the left subtree is too big,
2375 -- balanceR only checks whether the right subtree is too big.
2376
2377 -- balanceL is called when left subtree might have been inserted to or when
2378 -- right subtree might have been deleted from.
2379 balanceL :: k -> a -> Map k a -> Map k a -> Map k a
2380 balanceL k x l r = case r of
2381 Tip -> case l of
2382 Tip -> Bin 1 k x Tip Tip
2383 (Bin _ _ _ Tip Tip) -> Bin 2 k x l Tip
2384 (Bin _ lk lx Tip (Bin _ lrk lrx _ _)) -> Bin 3 lrk lrx (Bin 1 lk lx Tip Tip) (Bin 1 k x Tip Tip)
2385 (Bin _ lk lx ll@(Bin _ _ _ _ _) Tip) -> Bin 3 lk lx ll (Bin 1 k x Tip Tip)
2386 (Bin ls lk lx ll@(Bin lls _ _ _ _) lr@(Bin lrs lrk lrx lrl lrr))
2387 | lrs < ratio*lls -> Bin (1+ls) lk lx ll (Bin (1+lrs) k x lr Tip)
2388 | otherwise -> Bin (1+ls) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+size lrr) k x lrr Tip)
2389
2390 (Bin rs _ _ _ _) -> case l of
2391 Tip -> Bin (1+rs) k x Tip r
2392
2393 (Bin ls lk lx ll lr)
2394 | ls > delta*rs -> case (ll, lr) of
2395 (Bin lls _ _ _ _, Bin lrs lrk lrx lrl lrr)
2396 | lrs < ratio*lls -> Bin (1+ls+rs) lk lx ll (Bin (1+rs+lrs) k x lr r)
2397 | otherwise -> Bin (1+ls+rs) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+rs+size lrr) k x lrr r)
2398 (_, _) -> error "Failure in Data.Map.balanceL"
2399 | otherwise -> Bin (1+ls+rs) k x l r
2400 {-# NOINLINE balanceL #-}
2401
2402 -- balanceR is called when right subtree might have been inserted to or when
2403 -- left subtree might have been deleted from.
2404 balanceR :: k -> a -> Map k a -> Map k a -> Map k a
2405 balanceR k x l r = case l of
2406 Tip -> case r of
2407 Tip -> Bin 1 k x Tip Tip
2408 (Bin _ _ _ Tip Tip) -> Bin 2 k x Tip r
2409 (Bin _ rk rx Tip rr@(Bin _ _ _ _ _)) -> Bin 3 rk rx (Bin 1 k x Tip Tip) rr
2410 (Bin _ rk rx (Bin _ rlk rlx _ _) Tip) -> Bin 3 rlk rlx (Bin 1 k x Tip Tip) (Bin 1 rk rx Tip Tip)
2411 (Bin rs rk rx rl@(Bin rls rlk rlx rll rlr) rr@(Bin rrs _ _ _ _))
2412 | rls < ratio*rrs -> Bin (1+rs) rk rx (Bin (1+rls) k x Tip rl) rr
2413 | otherwise -> Bin (1+rs) rlk rlx (Bin (1+size rll) k x Tip rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
2414
2415 (Bin ls _ _ _ _) -> case r of
2416 Tip -> Bin (1+ls) k x l Tip
2417
2418 (Bin rs rk rx rl rr)
2419 | rs > delta*ls -> case (rl, rr) of
2420 (Bin rls rlk rlx rll rlr, Bin rrs _ _ _ _)
2421 | rls < ratio*rrs -> Bin (1+ls+rs) rk rx (Bin (1+ls+rls) k x l rl) rr
2422 | otherwise -> Bin (1+ls+rs) rlk rlx (Bin (1+ls+size rll) k x l rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
2423 (_, _) -> error "Failure in Data.Map.balanceR"
2424 | otherwise -> Bin (1+ls+rs) k x l r
2425 {-# NOINLINE balanceR #-}
2426
2427
2428 {--------------------------------------------------------------------
2429 The bin constructor maintains the size of the tree
2430 --------------------------------------------------------------------}
2431 bin :: k -> a -> Map k a -> Map k a -> Map k a
2432 bin k x l r
2433 = Bin (size l + size r + 1) k x l r
2434 {-# INLINE bin #-}
2435
2436
2437 {--------------------------------------------------------------------
2438 Eq converts the tree to a list. In a lazy setting, this
2439 actually seems one of the faster methods to compare two trees
2440 and it is certainly the simplest :-)
2441 --------------------------------------------------------------------}
2442 instance (Eq k,Eq a) => Eq (Map k a) where
2443 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
2444
2445 {--------------------------------------------------------------------
2446 Ord
2447 --------------------------------------------------------------------}
2448
2449 instance (Ord k, Ord v) => Ord (Map k v) where
2450 compare m1 m2 = compare (toAscList m1) (toAscList m2)
2451
2452 {--------------------------------------------------------------------
2453 Functor
2454 --------------------------------------------------------------------}
2455 instance Functor (Map k) where
2456 fmap f m = map f m
2457
2458 instance Traversable (Map k) where
2459 traverse _ Tip = pure Tip
2460 traverse f (Bin s k v l r)
2461 = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
2462
2463 instance Foldable.Foldable (Map k) where
2464 fold Tip = mempty
2465 fold (Bin _ _ v l r) = Foldable.fold l `mappend` v `mappend` Foldable.fold r
2466 foldr = foldr
2467 foldl = foldl
2468 foldMap _ Tip = mempty
2469 foldMap f (Bin _ _ v l r) = Foldable.foldMap f l `mappend` f v `mappend` Foldable.foldMap f r
2470
2471 {--------------------------------------------------------------------
2472 Read
2473 --------------------------------------------------------------------}
2474 instance (Ord k, Read k, Read e) => Read (Map k e) where
2475 #ifdef __GLASGOW_HASKELL__
2476 readPrec = parens $ prec 10 $ do
2477 Ident "fromList" <- lexP
2478 xs <- readPrec
2479 return (fromList xs)
2480
2481 readListPrec = readListPrecDefault
2482 #else
2483 readsPrec p = readParen (p > 10) $ \ r -> do
2484 ("fromList",s) <- lex r
2485 (xs,t) <- reads s
2486 return (fromList xs,t)
2487 #endif
2488
2489 {--------------------------------------------------------------------
2490 Show
2491 --------------------------------------------------------------------}
2492 instance (Show k, Show a) => Show (Map k a) where
2493 showsPrec d m = showParen (d > 10) $
2494 showString "fromList " . shows (toList m)
2495
2496 -- | /O(n)/. Show the tree that implements the map. The tree is shown
2497 -- in a compressed, hanging format. See 'showTreeWith'.
2498 showTree :: (Show k,Show a) => Map k a -> String
2499 showTree m
2500 = showTreeWith showElem True False m
2501 where
2502 showElem k x = show k ++ ":=" ++ show x
2503
2504
2505 {- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
2506 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
2507 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
2508 @wide@ is 'True', an extra wide version is shown.
2509
2510 > Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
2511 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
2512 > (4,())
2513 > +--(2,())
2514 > | +--(1,())
2515 > | +--(3,())
2516 > +--(5,())
2517 >
2518 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
2519 > (4,())
2520 > |
2521 > +--(2,())
2522 > | |
2523 > | +--(1,())
2524 > | |
2525 > | +--(3,())
2526 > |
2527 > +--(5,())
2528 >
2529 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
2530 > +--(5,())
2531 > |
2532 > (4,())
2533 > |
2534 > | +--(3,())
2535 > | |
2536 > +--(2,())
2537 > |
2538 > +--(1,())
2539
2540 -}
2541 showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
2542 showTreeWith showelem hang wide t
2543 | hang = (showsTreeHang showelem wide [] t) ""
2544 | otherwise = (showsTree showelem wide [] [] t) ""
2545
2546 showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
2547 showsTree showelem wide lbars rbars t
2548 = case t of
2549 Tip -> showsBars lbars . showString "|\n"
2550 Bin _ kx x Tip Tip
2551 -> showsBars lbars . showString (showelem kx x) . showString "\n"
2552 Bin _ kx x l r
2553 -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
2554 showWide wide rbars .
2555 showsBars lbars . showString (showelem kx x) . showString "\n" .
2556 showWide wide lbars .
2557 showsTree showelem wide (withEmpty lbars) (withBar lbars) l
2558
2559 showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
2560 showsTreeHang showelem wide bars t
2561 = case t of
2562 Tip -> showsBars bars . showString "|\n"
2563 Bin _ kx x Tip Tip
2564 -> showsBars bars . showString (showelem kx x) . showString "\n"
2565 Bin _ kx x l r
2566 -> showsBars bars . showString (showelem kx x) . showString "\n" .
2567 showWide wide bars .
2568 showsTreeHang showelem wide (withBar bars) l .
2569 showWide wide bars .
2570 showsTreeHang showelem wide (withEmpty bars) r
2571
2572 showWide :: Bool -> [String] -> String -> String
2573 showWide wide bars
2574 | wide = showString (concat (reverse bars)) . showString "|\n"
2575 | otherwise = id
2576
2577 showsBars :: [String] -> ShowS
2578 showsBars bars
2579 = case bars of
2580 [] -> id
2581 _ -> showString (concat (reverse (tail bars))) . showString node
2582
2583 node :: String
2584 node = "+--"
2585
2586 withBar, withEmpty :: [String] -> [String]
2587 withBar bars = "| ":bars
2588 withEmpty bars = " ":bars
2589
2590 {--------------------------------------------------------------------
2591 Typeable
2592 --------------------------------------------------------------------}
2593
2594 #include "Typeable.h"
2595 INSTANCE_TYPEABLE2(Map,mapTc,"Map")
2596
2597 {--------------------------------------------------------------------
2598 Assertions
2599 --------------------------------------------------------------------}
2600 -- | /O(n)/. Test if the internal map structure is valid.
2601 --
2602 -- > valid (fromAscList [(3,"b"), (5,"a")]) == True
2603 -- > valid (fromAscList [(5,"a"), (3,"b")]) == False
2604
2605 valid :: Ord k => Map k a -> Bool
2606 valid t
2607 = balanced t && ordered t && validsize t
2608
2609 ordered :: Ord a => Map a b -> Bool
2610 ordered t
2611 = bounded (const True) (const True) t
2612 where
2613 bounded lo hi t'
2614 = case t' of
2615 Tip -> True
2616 Bin _ kx _ l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
2617
2618 -- | Exported only for "Debug.QuickCheck"
2619 balanced :: Map k a -> Bool
2620 balanced t
2621 = case t of
2622 Tip -> True
2623 Bin _ _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
2624 balanced l && balanced r
2625
2626 validsize :: Map a b -> Bool
2627 validsize t
2628 = (realsize t == Just (size t))
2629 where
2630 realsize t'
2631 = case t' of
2632 Tip -> Just 0
2633 Bin sz _ _ l r -> case (realsize l,realsize r) of
2634 (Just n,Just m) | n+m+1 == sz -> Just sz
2635 _ -> Nothing
2636
2637 {--------------------------------------------------------------------
2638 Utilities
2639 --------------------------------------------------------------------}
2640 foldlStrict :: (a -> b -> a) -> a -> [b] -> a
2641 foldlStrict f = go
2642 where
2643 go z [] = z
2644 go z (x:xs) = let z' = f z x in z' `seq` go z' xs
2645 {-# INLINE foldlStrict #-}