Ticket #8092: DataMap.hs

File DataMap.hs, 81.6 KB (added by sjcjoosten, 9 months ago)

added the unionWithMaybe function

Line 
1{-# OPTIONS_GHC -XNoBangPatterns -cpp -XStandaloneDeriving -XDeriveDataTypeable #-}
2
3-----------------------------------------------------------------------------
4-- |
5-- Module      :  Data.Map
6-- Copyright   :  (c) Daan Leijen 2002
7--                (c) Andriy Palamarchuk 2008
8-- License     :  BSD-style
9-- Maintainer  :  libraries@haskell.org
10-- Stability   :  provisional
11-- Portability :  portable
12--
13-- An efficient implementation of maps from keys to values (dictionaries).
14--
15-- Since many function names (but not the type name) clash with
16-- "Prelude" names, this module is usually imported @qualified@, e.g.
17--
18-- >  import Data.Map (Map)
19-- >  import qualified Data.Map as Map
20--
21-- The implementation of 'Map' is based on /size balanced/ binary trees (or
22-- trees of /bounded balance/) as described by:
23--
24--    * Stephen Adams, \"/Efficient sets: a balancing act/\",
25--      Journal of Functional Programming 3(4):553-562, October 1993,
26--      <http://www.swiss.ai.mit.edu/~adams/BB/>.
27--
28--    * J. Nievergelt and E.M. Reingold,
29--      \"/Binary search trees of bounded balance/\",
30--      SIAM journal of computing 2(1), March 1973.
31--
32-- Note that the implementation is /left-biased/ -- the elements of a
33-- first argument are always preferred to the second, for example in
34-- 'union' or 'insert'.
35--
36-- Operation comments contain the operation time complexity in
37-- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>.
38-----------------------------------------------------------------------------
39
40module Data.Map  ( 
41            -- * Map type
42              Map          -- instance Eq,Show,Read
43
44            -- * Operators
45            , (!), (\\)
46
47
48            -- * Query
49            , null
50            , size
51            , member
52            , notMember
53            , lookup
54            , findWithDefault
55           
56            -- * Construction
57            , empty
58            , singleton
59
60            -- ** Insertion
61            , insert
62            , insertWith, insertWithKey, insertLookupWithKey
63            , insertWith', insertWithKey'
64           
65            -- ** Delete\/Update
66            , delete
67            , adjust
68            , adjustWithKey
69            , update
70            , updateWithKey
71            , updateLookupWithKey
72            , alter
73
74            -- * Combine
75
76            -- ** Union
77            , union         
78            , unionWith         
79            , unionWithKey         
80            , unionWithMaybe
81            , unionWithMaybeKey
82            , unions
83            , unionsWith
84
85            -- ** Difference
86            , difference
87            , differenceWith
88            , differenceWithKey
89           
90            -- ** Intersection
91            , intersection           
92            , intersectionWith
93            , intersectionWithKey
94
95            -- * Traversal
96            -- ** Map
97            , map
98            , mapWithKey
99            , mapAccum
100            , mapAccumWithKey
101            , mapAccumRWithKey
102            , mapKeys
103            , mapKeysWith
104            , mapKeysMonotonic
105
106            -- ** Fold
107            , fold
108            , foldWithKey
109            , foldrWithKey
110            , foldlWithKey
111
112            -- * Conversion
113            , elems
114            , keys
115            , keysSet
116            , assocs
117           
118            -- ** Lists
119            , toList
120            , fromList
121            , fromListWith
122            , fromListWithKey
123
124            -- ** Ordered lists
125            , toAscList
126            , toDescList
127            , fromAscList
128            , fromAscListWith
129            , fromAscListWithKey
130            , fromDistinctAscList
131
132            -- * Filter
133            , filter
134            , filterWithKey
135            , partition
136            , partitionWithKey
137
138            , mapMaybe
139            , mapWithMaybeKey
140            , mapEither
141            , mapEitherWithKey
142
143            , split         
144            , splitLookup   
145
146            -- * Submap
147            , isSubmapOf, isSubmapOfBy
148            , isProperSubmapOf, isProperSubmapOfBy
149
150            -- * Indexed
151            , lookupIndex
152            , findIndex
153            , elemAt
154            , updateAt
155            , deleteAt
156
157            -- * Min\/Max
158            , findMin
159            , findMax
160            , deleteMin
161            , deleteMax
162            , deleteFindMin
163            , deleteFindMax
164            , updateMin
165            , updateMax
166            , updateMinWithKey
167            , updateMaxWithKey
168            , minView
169            , maxView
170            , minViewWithKey
171            , maxViewWithKey
172           
173            -- * Debugging
174            , showTree
175            , showTreeWith
176            , valid
177            ) where
178
179import Prelude hiding (lookup,map,filter,null)
180import qualified Data.Set as Set
181import qualified Data.List as List
182import Data.Monoid (Monoid(..))
183import Control.Applicative (Applicative(..), (<$>))
184import Data.Traversable (Traversable(traverse))
185import Data.Foldable (Foldable(foldMap))
186#ifndef __GLASGOW_HASKELL__
187import Data.Typeable ( Typeable, typeOf, typeOfDefault
188                     , Typeable1, typeOf1, typeOf1Default)
189#endif
190import Data.Typeable (Typeable2(..), TyCon, mkTyCon, mkTyConApp)
191
192{-
193-- for quick check
194import qualified Prelude
195import qualified List
196import Debug.QuickCheck       
197import List(nub,sort)   
198-}
199
200#if __GLASGOW_HASKELL__
201import Text.Read
202import Data.Data (Data(..), mkNoRepType, gcast2)
203#endif
204
205{--------------------------------------------------------------------
206  Operators
207--------------------------------------------------------------------}
208infixl 9 !,\\ --
209
210-- | /O(log n)/. Find the value at a key.
211-- Calls 'error' when the element can not be found.
212--
213-- > fromList [(5,'a'), (3,'b')] ! 1    Error: element not in the map
214-- > fromList [(5,'a'), (3,'b')] ! 5 == 'a'
215
216(!) :: Ord k => Map k a -> k -> a
217m ! k    = find k m
218
219-- | Same as 'difference'.
220(\\) :: Ord k => Map k a -> Map k b -> Map k a
221m1 \\ m2 = difference m1 m2
222
223{--------------------------------------------------------------------
224  Size balanced trees.
225--------------------------------------------------------------------}
226-- | A Map from keys @k@ to values @a@.
227data Map k a  = Tip 
228              | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a) 
229
230type Size     = Int
231
232instance (Ord k) => Monoid (Map k v) where
233    mempty  = empty
234    mappend = union
235    mconcat = unions
236
237#if __GLASGOW_HASKELL__
238
239{--------------------------------------------------------------------
240  A Data instance 
241--------------------------------------------------------------------}
242
243-- This instance preserves data abstraction at the cost of inefficiency.
244-- We omit reflection services for the sake of data abstraction.
245
246instance (Data k, Data a, Ord k) => Data (Map k a) where
247  gfoldl f z m   = z fromList `f` toList m
248  toConstr _     = error "toConstr"
249  gunfold _ _    = error "gunfold"
250  dataTypeOf _   = mkNoRepType "Data.Map.Map"
251  dataCast2 f    = gcast2 f
252
253#endif
254
255{--------------------------------------------------------------------
256  Query
257--------------------------------------------------------------------}
258-- | /O(1)/. Is the map empty?
259--
260-- > Data.Map.null (empty)           == True
261-- > Data.Map.null (singleton 1 'a') == False
262
263null :: Map k a -> Bool
264null t
265  = case t of
266      Tip    -> True
267      Bin {} -> False
268
269-- | /O(1)/. The number of elements in the map.
270--
271-- > size empty                                   == 0
272-- > size (singleton 1 'a')                       == 1
273-- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
274
275size :: Map k a -> Int
276size t
277  = case t of
278      Tip             -> 0
279      Bin sz _ _ _ _  -> sz
280
281
282-- | /O(log n)/. Lookup the value at a key in the map.
283--
284-- The function will return the corresponding value as @('Just' value)@,
285-- or 'Nothing' if the key isn't in the map.
286--
287-- An example of using @lookup@:
288--
289-- > import Prelude hiding (lookup)
290-- > import Data.Map
291-- >
292-- > employeeDept = fromList([("John","Sales"), ("Bob","IT")])
293-- > deptCountry = fromList([("IT","USA"), ("Sales","France")])
294-- > countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")])
295-- >
296-- > employeeCurrency :: String -> Maybe String
297-- > employeeCurrency name = do
298-- >     dept <- lookup name employeeDept
299-- >     country <- lookup dept deptCountry
300-- >     lookup country countryCurrency
301-- >
302-- > main = do
303-- >     putStrLn $ "John's currency: " ++ (show (employeeCurrency "John"))
304-- >     putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))
305--
306-- The output of this program:
307--
308-- >   John's currency: Just "Euro"
309-- >   Pete's currency: Nothing
310
311lookup :: Ord k => k -> Map k a -> Maybe a
312lookup k t
313  = case t of
314      Tip -> Nothing
315      Bin _ kx x l r
316          -> case compare k kx of
317               LT -> lookup k l
318               GT -> lookup k r
319               EQ -> Just x       
320
321lookupAssoc :: Ord k => k -> Map k a -> Maybe (k,a)
322lookupAssoc  k t
323  = case t of
324      Tip -> Nothing
325      Bin _ kx x l r
326          -> case compare k kx of
327               LT -> lookupAssoc k l
328               GT -> lookupAssoc k r
329               EQ -> Just (kx,x)
330
331-- | /O(log n)/. Is the key a member of the map? See also 'notMember'.
332--
333-- > member 5 (fromList [(5,'a'), (3,'b')]) == True
334-- > member 1 (fromList [(5,'a'), (3,'b')]) == False
335
336member :: Ord k => k -> Map k a -> Bool
337member k m
338  = case lookup k m of
339      Nothing -> False
340      Just _  -> True
341
342-- | /O(log n)/. Is the key not a member of the map? See also 'member'.
343--
344-- > notMember 5 (fromList [(5,'a'), (3,'b')]) == False
345-- > notMember 1 (fromList [(5,'a'), (3,'b')]) == True
346
347notMember :: Ord k => k -> Map k a -> Bool
348notMember k m = not $ member k m
349
350-- | /O(log n)/. Find the value at a key.
351-- Calls 'error' when the element can not be found.
352find :: Ord k => k -> Map k a -> a
353find k m
354  = case lookup k m of
355      Nothing -> error "Map.find: element not in the map"
356      Just x  -> x
357
358-- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
359-- the value at key @k@ or returns default value @def@
360-- when the key is not in the map.
361--
362-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
363-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
364
365findWithDefault :: Ord k => a -> k -> Map k a -> a
366findWithDefault def k m
367  = case lookup k m of
368      Nothing -> def
369      Just x  -> x
370
371
372
373{--------------------------------------------------------------------
374  Construction
375--------------------------------------------------------------------}
376-- | /O(1)/. The empty map.
377--
378-- > empty      == fromList []
379-- > size empty == 0
380
381empty :: Map k a
382empty 
383  = Tip
384
385-- | /O(1)/. A map with a single element.
386--
387-- > singleton 1 'a'        == fromList [(1, 'a')]
388-- > size (singleton 1 'a') == 1
389
390singleton :: k -> a -> Map k a
391singleton k x 
392  = Bin 1 k x Tip Tip
393
394{--------------------------------------------------------------------
395  Insertion
396--------------------------------------------------------------------}
397-- | /O(log n)/. Insert a new key and value in the map.
398-- If the key is already present in the map, the associated value is
399-- replaced with the supplied value. 'insert' is equivalent to
400-- @'insertWith' 'const'@.
401--
402-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
403-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
404-- > insert 5 'x' empty                         == singleton 5 'x'
405
406insert :: Ord k => k -> a -> Map k a -> Map k a
407insert kx x t
408  = case t of
409      Tip -> singleton kx x
410      Bin sz ky y l r
411          -> case compare kx ky of
412               LT -> balance ky y (insert kx x l) r
413               GT -> balance ky y l (insert kx x r)
414               EQ -> Bin sz kx x l r
415
416-- | /O(log n)/. Insert with a function, combining new value and old value.
417-- @'insertWith' f key value mp@
418-- will insert the pair (key, value) into @mp@ if key does
419-- not exist in the map. If the key does exist, the function will
420-- insert the pair @(key, f new_value old_value)@.
421--
422-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
423-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
424-- > insertWith (++) 5 "xxx" empty                         == singleton 5 "xxx"
425
426insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
427insertWith f k x m         
428  = insertWithKey (\_ x' y' -> f x' y') k x m
429
430-- | Same as 'insertWith', but the combining function is applied strictly.
431insertWith' :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
432insertWith' f k x m         
433  = insertWithKey' (\_ x' y' -> f x' y') k x m
434
435
436-- | /O(log n)/. Insert with a function, combining key, new value and old value.
437-- @'insertWithKey' f key value mp@
438-- will insert the pair (key, value) into @mp@ if key does
439-- not exist in the map. If the key does exist, the function will
440-- insert the pair @(key,f key new_value old_value)@.
441-- Note that the key passed to f is the same key passed to 'insertWithKey'.
442--
443-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
444-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
445-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
446-- > insertWithKey f 5 "xxx" empty                         == singleton 5 "xxx"
447
448insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
449insertWithKey f kx x t
450  = case t of
451      Tip -> singleton kx x
452      Bin sy ky y l r
453          -> case compare kx ky of
454               LT -> balance ky y (insertWithKey f kx x l) r
455               GT -> balance ky y l (insertWithKey f kx x r)
456               EQ -> Bin sy kx (f kx x y) l r
457
458-- | Same as 'insertWithKey', but the combining function is applied strictly.
459insertWithKey' :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
460insertWithKey' f kx x t
461  = case t of
462      Tip -> singleton kx x
463      Bin sy ky y l r
464          -> case compare kx ky of
465               LT -> balance ky y (insertWithKey' f kx x l) r
466               GT -> balance ky y l (insertWithKey' f kx x r)
467               EQ -> let x' = f kx x y in seq x' (Bin sy kx x' l r)
468
469
470-- | /O(log n)/. Combines insert operation with old value retrieval.
471-- The expression (@'insertLookupWithKey' f k x map@)
472-- is a pair where the first element is equal to (@'lookup' k map@)
473-- and the second element equal to (@'insertWithKey' f k x map@).
474--
475-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
476-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
477-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing,  fromList [(3, "b"), (5, "a"), (7, "xxx")])
478-- > insertLookupWithKey f 5 "xxx" empty                         == (Nothing,  singleton 5 "xxx")
479--
480-- This is how to define @insertLookup@ using @insertLookupWithKey@:
481--
482-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
483-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
484-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing,  fromList [(3, "b"), (5, "a"), (7, "x")])
485
486insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
487insertLookupWithKey f kx x t
488  = case t of
489      Tip -> (Nothing, singleton kx x)
490      Bin sy ky y l r
491          -> case compare kx ky of
492               LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
493               GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
494               EQ -> (Just y, Bin sy kx (f kx x y) l r)
495
496{--------------------------------------------------------------------
497  Deletion
498  [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
499--------------------------------------------------------------------}
500-- | /O(log n)/. Delete a key and its value from the map. When the key is not
501-- a member of the map, the original map is returned.
502--
503-- > delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
504-- > delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
505-- > delete 5 empty                         == empty
506
507delete :: Ord k => k -> Map k a -> Map k a
508delete k t
509  = case t of
510      Tip -> Tip
511      Bin _ kx x l r
512          -> case compare k kx of
513               LT -> balance kx x (delete k l) r
514               GT -> balance kx x l (delete k r)
515               EQ -> glue l r
516
517-- | /O(log n)/. Update a value at a specific key with the result of the provided function.
518-- When the key is not
519-- a member of the map, the original map is returned.
520--
521-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
522-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
523-- > adjust ("new " ++) 7 empty                         == empty
524
525adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
526adjust f k m
527  = adjustWithKey (\_ x -> f x) k m
528
529-- | /O(log n)/. Adjust a value at a specific key. When the key is not
530-- a member of the map, the original map is returned.
531--
532-- > let f key x = (show key) ++ ":new " ++ x
533-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
534-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
535-- > adjustWithKey f 7 empty                         == empty
536
537adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
538adjustWithKey f k m
539  = updateWithKey (\k' x' -> Just (f k' x')) k m
540
541-- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
542-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
543-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
544--
545-- > let f x = if x == "a" then Just "new a" else Nothing
546-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
547-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
548-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
549
550update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
551update f k m
552  = updateWithKey (\_ x -> f x) k m
553
554-- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
555-- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
556-- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
557-- to the new value @y@.
558--
559-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
560-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
561-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
562-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
563
564updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
565updateWithKey f k t
566  = case t of
567      Tip -> Tip
568      Bin sx kx x l r
569          -> case compare k kx of
570               LT -> balance kx x (updateWithKey f k l) r
571               GT -> balance kx x l (updateWithKey f k r)
572               EQ -> case f kx x of
573                       Just x' -> Bin sx kx x' l r
574                       Nothing -> glue l r
575
576-- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
577-- The function returns changed value, if it is updated.
578-- Returns the original key value if the map entry is deleted.
579--
580-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
581-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
582-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing,  fromList [(3, "b"), (5, "a")])
583-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
584
585updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
586updateLookupWithKey f k t
587  = case t of
588      Tip -> (Nothing,Tip)
589      Bin sx kx x l r
590          -> case compare k kx of
591               LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
592               GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r') 
593               EQ -> case f kx x of
594                       Just x' -> (Just x',Bin sx kx x' l r)
595                       Nothing -> (Just x,glue l r)
596
597-- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
598-- 'alter' can be used to insert, delete, or update a value in a 'Map'.
599-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
600--
601-- > let f _ = Nothing
602-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
603-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
604-- >
605-- > let f _ = Just "c"
606-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
607-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
608
609alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
610alter f k t
611  = case t of
612      Tip -> case f Nothing of
613               Nothing -> Tip
614               Just x -> singleton k x
615      Bin sx kx x l r
616          -> case compare k kx of
617               LT -> balance kx x (alter f k l) r
618               GT -> balance kx x l (alter f k r)
619               EQ -> case f (Just x) of
620                       Just x' -> Bin sx kx x' l r
621                       Nothing -> glue l r
622
623{--------------------------------------------------------------------
624  Indexing
625--------------------------------------------------------------------}
626-- | /O(log n)/. Return the /index/ of a key. The index is a number from
627-- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
628-- the key is not a 'member' of the map.
629--
630-- > findIndex 2 (fromList [(5,"a"), (3,"b")])    Error: element is not in the map
631-- > findIndex 3 (fromList [(5,"a"), (3,"b")]) == 0
632-- > findIndex 5 (fromList [(5,"a"), (3,"b")]) == 1
633-- > findIndex 6 (fromList [(5,"a"), (3,"b")])    Error: element is not in the map
634
635findIndex :: Ord k => k -> Map k a -> Int
636findIndex k t
637  = case lookupIndex k t of
638      Nothing  -> error "Map.findIndex: element is not in the map"
639      Just idx -> idx
640
641-- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
642-- /0/ up to, but not including, the 'size' of the map.
643--
644-- > isJust (lookupIndex 2 (fromList [(5,"a"), (3,"b")]))   == False
645-- > fromJust (lookupIndex 3 (fromList [(5,"a"), (3,"b")])) == 0
646-- > fromJust (lookupIndex 5 (fromList [(5,"a"), (3,"b")])) == 1
647-- > isJust (lookupIndex 6 (fromList [(5,"a"), (3,"b")]))   == False
648
649lookupIndex :: Ord k => k -> Map k a -> Maybe Int
650lookupIndex k t = f 0 t
651  where
652    f _   Tip  = Nothing
653    f idx (Bin _ kx _ l r)
654      = case compare k kx of
655          LT -> f idx l
656          GT -> f (idx + size l + 1) r
657          EQ -> Just (idx + size l)
658
659-- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
660-- invalid index is used.
661--
662-- > elemAt 0 (fromList [(5,"a"), (3,"b")]) == (3,"b")
663-- > elemAt 1 (fromList [(5,"a"), (3,"b")]) == (5, "a")
664-- > elemAt 2 (fromList [(5,"a"), (3,"b")])    Error: index out of range
665
666elemAt :: Int -> Map k a -> (k,a)
667elemAt _ Tip = error "Map.elemAt: index out of range"
668elemAt i (Bin _ kx x l r)
669  = case compare i sizeL of
670      LT -> elemAt i l
671      GT -> elemAt (i-sizeL-1) r
672      EQ -> (kx,x)
673  where
674    sizeL = size l
675
676-- | /O(log n)/. Update the element at /index/. Calls 'error' when an
677-- invalid index is used.
678--
679-- > updateAt (\ _ _ -> Just "x") 0    (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
680-- > updateAt (\ _ _ -> Just "x") 1    (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
681-- > updateAt (\ _ _ -> Just "x") 2    (fromList [(5,"a"), (3,"b")])    Error: index out of range
682-- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")])    Error: index out of range
683-- > updateAt (\_ _  -> Nothing)  0    (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
684-- > updateAt (\_ _  -> Nothing)  1    (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
685-- > updateAt (\_ _  -> Nothing)  2    (fromList [(5,"a"), (3,"b")])    Error: index out of range
686-- > updateAt (\_ _  -> Nothing)  (-1) (fromList [(5,"a"), (3,"b")])    Error: index out of range
687
688updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
689updateAt _ _ Tip  = error "Map.updateAt: index out of range"
690updateAt f i (Bin sx kx x l r)
691  = case compare i sizeL of
692      LT -> balance kx x (updateAt f i l) r
693      GT -> balance kx x l (updateAt f (i-sizeL-1) r)
694      EQ -> case f kx x of
695              Just x' -> Bin sx kx x' l r
696              Nothing -> glue l r
697  where
698    sizeL = size l
699
700-- | /O(log n)/. Delete the element at /index/.
701-- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
702--
703-- > deleteAt 0  (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
704-- > deleteAt 1  (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
705-- > deleteAt 2 (fromList [(5,"a"), (3,"b")])     Error: index out of range
706-- > deleteAt (-1) (fromList [(5,"a"), (3,"b")])  Error: index out of range
707
708deleteAt :: Int -> Map k a -> Map k a
709deleteAt i m
710  = updateAt (\_ _ -> Nothing) i m
711
712
713{--------------------------------------------------------------------
714  Minimal, Maximal
715--------------------------------------------------------------------}
716-- | /O(log n)/. The minimal key of the map. Calls 'error' is the map is empty.
717--
718-- > findMin (fromList [(5,"a"), (3,"b")]) == (3,"b")
719-- > findMin empty                            Error: empty map has no minimal element
720
721findMin :: Map k a -> (k,a)
722findMin (Bin _ kx x Tip _)  = (kx,x)
723findMin (Bin _ _  _ l _)    = findMin l
724findMin Tip                 = error "Map.findMin: empty map has no minimal element"
725
726-- | /O(log n)/. The maximal key of the map. Calls 'error' is the map is empty.
727--
728-- > findMax (fromList [(5,"a"), (3,"b")]) == (5,"a")
729-- > findMax empty                            Error: empty map has no maximal element
730
731findMax :: Map k a -> (k,a)
732findMax (Bin _ kx x _ Tip)  = (kx,x)
733findMax (Bin _ _  _ _ r)    = findMax r
734findMax Tip                 = error "Map.findMax: empty map has no maximal element"
735
736-- | /O(log n)/. Delete the minimal key. Returns an empty map if the map is empty.
737--
738-- > deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")]
739-- > deleteMin empty == empty
740
741deleteMin :: Map k a -> Map k a
742deleteMin (Bin _ _  _ Tip r)  = r
743deleteMin (Bin _ kx x l r)    = balance kx x (deleteMin l) r
744deleteMin Tip                 = Tip
745
746-- | /O(log n)/. Delete the maximal key. Returns an empty map if the map is empty.
747--
748-- > deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")]
749-- > deleteMax empty == empty
750
751deleteMax :: Map k a -> Map k a
752deleteMax (Bin _ _  _ l Tip)  = l
753deleteMax (Bin _ kx x l r)    = balance kx x l (deleteMax r)
754deleteMax Tip                 = Tip
755
756-- | /O(log n)/. Update the value at the minimal key.
757--
758-- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
759-- > updateMin (\ _ -> Nothing)         (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
760
761updateMin :: (a -> Maybe a) -> Map k a -> Map k a
762updateMin f m
763  = updateMinWithKey (\_ x -> f x) m
764
765-- | /O(log n)/. Update the value at the maximal key.
766--
767-- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
768-- > updateMax (\ _ -> Nothing)         (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
769
770updateMax :: (a -> Maybe a) -> Map k a -> Map k a
771updateMax f m
772  = updateMaxWithKey (\_ x -> f x) m
773
774
775-- | /O(log n)/. Update the value at the minimal key.
776--
777-- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
778-- > updateMinWithKey (\ _ _ -> Nothing)                     (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
779
780updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
781updateMinWithKey f t
782  = case t of
783      Bin sx kx x Tip r  -> case f kx x of
784                              Nothing -> r
785                              Just x' -> Bin sx kx x' Tip r
786      Bin _ kx x l r     -> balance kx x (updateMinWithKey f l) r
787      Tip                -> Tip
788
789-- | /O(log n)/. Update the value at the maximal key.
790--
791-- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
792-- > updateMaxWithKey (\ _ _ -> Nothing)                     (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
793
794updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
795updateMaxWithKey f t
796  = case t of
797      Bin sx kx x l Tip  -> case f kx x of
798                              Nothing -> l
799                              Just x' -> Bin sx kx x' l Tip
800      Bin _ kx x l r     -> balance kx x l (updateMaxWithKey f r)
801      Tip                -> Tip
802
803-- | /O(log n)/. Retrieves the minimal (key,value) pair of the map, and
804-- the map stripped of that element, or 'Nothing' if passed an empty map.
805--
806-- > minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
807-- > minViewWithKey empty == Nothing
808
809minViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
810minViewWithKey Tip = Nothing
811minViewWithKey x = Just (deleteFindMin x)
812
813-- | /O(log n)/. Retrieves the maximal (key,value) pair of the map, and
814-- the map stripped of that element, or 'Nothing' if passed an empty map.
815--
816-- > maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
817-- > maxViewWithKey empty == Nothing
818
819maxViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
820maxViewWithKey Tip = Nothing
821maxViewWithKey x = Just (deleteFindMax x)
822
823-- | /O(log n)/. Retrieves the value associated with minimal key of the
824-- map, and the map stripped of that element, or 'Nothing' if passed an
825-- empty map.
826--
827-- > minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a")
828-- > minView empty == Nothing
829
830minView :: Map k a -> Maybe (a, Map k a)
831minView Tip = Nothing
832minView x = Just (first snd $ deleteFindMin x)
833
834-- | /O(log n)/. Retrieves the value associated with maximal key of the
835-- map, and the map stripped of that element, or 'Nothing' if passed an
836--
837-- > maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b")
838-- > maxView empty == Nothing
839
840maxView :: Map k a -> Maybe (a, Map k a)
841maxView Tip = Nothing
842maxView x = Just (first snd $ deleteFindMax x)
843
844-- Update the 1st component of a tuple (special case of Control.Arrow.first)
845first :: (a -> b) -> (a,c) -> (b,c)
846first f (x,y) = (f x, y)
847
848{--------------------------------------------------------------------
849  Union.
850--------------------------------------------------------------------}
851-- | The union of a list of maps:
852--   (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
853--
854-- > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
855-- >     == fromList [(3, "b"), (5, "a"), (7, "C")]
856-- > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
857-- >     == fromList [(3, "B3"), (5, "A3"), (7, "C")]
858
859unions :: Ord k => [Map k a] -> Map k a
860unions ts
861  = foldlStrict union empty ts
862
863-- | The union of a list of maps, with a combining operation:
864--   (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
865--
866-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
867-- >     == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
868
869unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
870unionsWith f ts
871  = foldlStrict (unionWith f) empty ts
872
873-- | /O(n+m)/.
874-- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
875-- It prefers @t1@ when duplicate keys are encountered,
876-- i.e. (@'union' == 'unionWith' 'const'@).
877-- The implementation uses the efficient /hedge-union/ algorithm.
878-- Hedge-union is more efficient on (bigset \``union`\` smallset).
879--
880-- > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]
881
882union :: Ord k => Map k a -> Map k a -> Map k a
883union Tip t2  = t2
884union t1 Tip  = t1
885union t1 t2 = hedgeUnionL (const LT) (const GT) t1 t2
886
887-- left-biased hedge union
888hedgeUnionL :: Ord a
889            => (a -> Ordering) -> (a -> Ordering) -> Map a b -> Map a b
890            -> Map a b
891hedgeUnionL _     _     t1 Tip
892  = t1
893hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
894  = join kx x (filterGt cmplo l) (filterLt cmphi r)
895hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
896  = join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2)) 
897              (hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
898  where
899    cmpkx k  = compare kx k
900
901{-
902XXX unused code
903
904-- right-biased hedge union
905hedgeUnionR :: Ord a
906            => (a -> Ordering) -> (a -> Ordering) -> Map a b -> Map a b
907            -> Map a b
908hedgeUnionR _     _     t1 Tip
909  = t1
910hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
911  = join kx x (filterGt cmplo l) (filterLt cmphi r)
912hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
913  = join kx newx (hedgeUnionR cmplo cmpkx l lt)
914                 (hedgeUnionR cmpkx cmphi r gt)
915  where
916    cmpkx k     = compare kx k
917    lt          = trim cmplo cmpkx t2
918    (found,gt)  = trimLookupLo kx cmphi t2
919    newx        = case found of
920                    Nothing -> x
921                    Just (_,y) -> y
922-}
923
924{--------------------------------------------------------------------
925  Union with a combining function
926--------------------------------------------------------------------}
927-- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
928--
929-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
930
931unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
932unionWith f m1 m2
933  = unionWithKey (\_ x y -> f x y) m1 m2
934
935unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
936unionWithKey _ Tip t2  = t2
937unionWithKey _ t1 Tip  = t1
938unionWithKey f t1 t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
939
940hedgeUnionWithKey :: Ord a
941                  => (a -> b -> b -> b)
942                  -> (a -> Ordering) -> (a -> Ordering)
943                  -> Map a b -> Map a b
944                  -> Map a b
945hedgeUnionWithKey _ _     _     t1 Tip
946  = t1
947hedgeUnionWithKey _ cmplo cmphi Tip (Bin _ kx x l r)
948  = join kx x (filterGt cmplo l) (filterLt cmphi r)
949hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
950  = join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt) 
951                 (hedgeUnionWithKey f cmpkx cmphi r gt)
952  where
953    cmpkx k     = compare kx k
954    lt          = trim cmplo cmpkx t2
955    (found,gt)  = trimLookupLo kx cmphi t2
956    newx        = case found of
957                    Nothing -> x
958                    Just (_,y) -> f kx x y
959
960{--------------------------------------------------------------------
961  Difference
962--------------------------------------------------------------------}
963-- | /O(n+m)/. Difference of two maps.
964-- Return elements of the first map not existing in the second map.
965-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
966--
967-- > difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"
968
969difference :: Ord k => Map k a -> Map k b -> Map k a
970difference Tip _   = Tip
971difference t1 Tip  = t1
972difference t1 t2   = hedgeDiff (const LT) (const GT) t1 t2
973
974hedgeDiff :: Ord a
975          => (a -> Ordering) -> (a -> Ordering) -> Map a b -> Map a c
976          -> Map a b
977hedgeDiff _     _     Tip _
978  = Tip
979hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip 
980  = join kx x (filterGt cmplo l) (filterLt cmphi r)
981hedgeDiff cmplo cmphi t (Bin _ kx _ l r) 
982  = merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l) 
983          (hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
984  where
985    cmpkx k = compare kx k   
986
987-- | /O(n+m)/. Difference with a combining function.
988-- When two equal keys are
989-- encountered, the combining function is applied to the values of these keys.
990-- If it returns 'Nothing', the element is discarded (proper set difference). If
991-- it returns (@'Just' y@), the element is updated with a new value @y@.
992-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
993--
994-- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
995-- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
996-- >     == singleton 3 "b:B"
997
998differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
999differenceWith f m1 m2
1000  = differenceWithKey (\_ x y -> f x y) m1 m2
1001
1002-- | /O(n+m)/. Difference with a combining function. When two equal keys are
1003-- encountered, the combining function is applied to the key and both values.
1004-- If it returns 'Nothing', the element is discarded (proper set difference). If
1005-- it returns (@'Just' y@), the element is updated with a new value @y@.
1006-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
1007--
1008-- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
1009-- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
1010-- >     == singleton 3 "3:b|B"
1011
1012differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
1013differenceWithKey _ Tip _   = Tip
1014differenceWithKey _ t1 Tip  = t1
1015differenceWithKey f t1 t2   = hedgeDiffWithKey f (const LT) (const GT) t1 t2
1016
1017hedgeDiffWithKey :: Ord a
1018                 => (a -> b -> c -> Maybe b)
1019                 -> (a -> Ordering) -> (a -> Ordering)
1020                 -> Map a b -> Map a c
1021                 -> Map a b
1022hedgeDiffWithKey _ _     _     Tip _
1023  = Tip
1024hedgeDiffWithKey _ cmplo cmphi (Bin _ kx x l r) Tip
1025  = join kx x (filterGt cmplo l) (filterLt cmphi r)
1026hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r) 
1027  = case found of
1028      Nothing -> merge tl tr
1029      Just (ky,y) -> 
1030          case f ky y x of
1031            Nothing -> merge tl tr
1032            Just z  -> join ky z tl tr
1033  where
1034    cmpkx k     = compare kx k   
1035    lt          = trim cmplo cmpkx t
1036    (found,gt)  = trimLookupLo kx cmphi t
1037    tl          = hedgeDiffWithKey f cmplo cmpkx lt l
1038    tr          = hedgeDiffWithKey f cmpkx cmphi gt r
1039
1040
1041
1042{--------------------------------------------------------------------
1043  Intersection
1044--------------------------------------------------------------------}
1045-- | /O(n+m)/. Intersection of two maps.
1046-- Return data in the first map for the keys existing in both maps.
1047-- (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
1048--
1049-- > intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"
1050
1051intersection :: Ord k => Map k a -> Map k b -> Map k a
1052intersection m1 m2
1053  = intersectionWithKey (\_ x _ -> x) m1 m2
1054
1055-- | /O(n+m)/. Intersection with a combining function.
1056--
1057-- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
1058
1059intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
1060intersectionWith f m1 m2
1061  = intersectionWithKey (\_ x y -> f x y) m1 m2
1062
1063-- | /O(n+m)/. Intersection with a combining function.
1064-- Intersection is more efficient on (bigset \``intersection`\` smallset).
1065--
1066-- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
1067-- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
1068
1069--intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
1070--intersectionWithKey f Tip t = Tip
1071--intersectionWithKey f t Tip = Tip
1072--intersectionWithKey f t1 t2 = intersectWithKey f t1 t2
1073--
1074--intersectWithKey f Tip t = Tip
1075--intersectWithKey f t Tip = Tip
1076--intersectWithKey f t (Bin _ kx x l r)
1077--  = case found of
1078--      Nothing -> merge tl tr
1079--      Just y  -> join kx (f kx y x) tl tr
1080--  where
1081--    (lt,found,gt) = splitLookup kx t
1082--    tl            = intersectWithKey f lt l
1083--    tr            = intersectWithKey f gt r
1084
1085intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
1086intersectionWithKey _ Tip _ = Tip
1087intersectionWithKey _ _ Tip = Tip
1088intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
1089   if s1 >= s2 then
1090      let (lt,found,gt) = splitLookupWithKey k2 t1
1091          tl            = intersectionWithKey f lt l2
1092          tr            = intersectionWithKey f gt r2
1093      in case found of
1094      Just (k,x) -> join k (f k x x2) tl tr
1095      Nothing -> merge tl tr
1096   else let (lt,found,gt) = splitLookup k1 t2
1097            tl            = intersectionWithKey f l1 lt
1098            tr            = intersectionWithKey f r1 gt
1099      in case found of
1100      Just x -> join k1 (f k1 x1 x) tl tr
1101      Nothing -> merge tl tr
1102
1103
1104
1105{--------------------------------------------------------------------
1106  Submap
1107--------------------------------------------------------------------}
1108-- | /O(n+m)/.
1109-- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
1110--
1111isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
1112isSubmapOf m1 m2
1113  = isSubmapOfBy (==) m1 m2
1114
1115{- | /O(n+m)/.
1116 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
1117 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
1118 applied to their respective values. For example, the following
1119 expressions are all 'True':
1120 
1121 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1122 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1123 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
1124
1125 But the following are all 'False':
1126 
1127 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
1128 > isSubmapOfBy (<)  (fromList [('a',1)]) (fromList [('a',1),('b',2)])
1129 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
1130 
1131
1132-}
1133isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
1134isSubmapOfBy f t1 t2
1135  = (size t1 <= size t2) && (submap' f t1 t2)
1136
1137submap' :: Ord a => (b -> c -> Bool) -> Map a b -> Map a c -> Bool
1138submap' _ Tip _ = True
1139submap' _ _ Tip = False
1140submap' f (Bin _ kx x l r) t
1141  = case found of
1142      Nothing -> False
1143      Just y  -> f x y && submap' f l lt && submap' f r gt
1144  where
1145    (lt,found,gt) = splitLookup kx t
1146
1147-- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
1148-- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
1149isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
1150isProperSubmapOf m1 m2
1151  = isProperSubmapOfBy (==) m1 m2
1152
1153{- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
1154 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
1155 @m1@ and @m2@ are not equal,
1156 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
1157 applied to their respective values. For example, the following
1158 expressions are all 'True':
1159 
1160  > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
1161  > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
1162
1163 But the following are all 'False':
1164 
1165  > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
1166  > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
1167  > isProperSubmapOfBy (<)  (fromList [(1,1)])       (fromList [(1,1),(2,2)])
1168 
1169 
1170-}
1171isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
1172isProperSubmapOfBy f t1 t2
1173  = (size t1 < size t2) && (submap' f t1 t2)
1174
1175{--------------------------------------------------------------------
1176  Filter and partition
1177--------------------------------------------------------------------}
1178-- | /O(n)/. Filter all values that satisfy the predicate.
1179--
1180-- > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
1181-- > filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
1182-- > filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty
1183
1184filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
1185filter p m
1186  = filterWithKey (\_ x -> p x) m
1187
1188-- | /O(n)/. Filter all keys\/values that satisfy the predicate.
1189--
1190-- > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
1191
1192filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
1193filterWithKey _ Tip = Tip
1194filterWithKey p (Bin _ kx x l r)
1195  | p kx x    = join kx x (filterWithKey p l) (filterWithKey p r)
1196  | otherwise = merge (filterWithKey p l) (filterWithKey p r)
1197
1198
1199-- | /O(n)/. Partition the map according to a predicate. The first
1200-- map contains all elements that satisfy the predicate, the second all
1201-- elements that fail the predicate. See also 'split'.
1202--
1203-- > partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
1204-- > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
1205-- > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
1206
1207partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
1208partition p m
1209  = partitionWithKey (\_ x -> p x) m
1210
1211-- | /O(n)/. Partition the map according to a predicate. The first
1212-- map contains all elements that satisfy the predicate, the second all
1213-- elements that fail the predicate. See also 'split'.
1214--
1215-- > partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
1216-- > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
1217-- > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
1218
1219partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
1220partitionWithKey _ Tip = (Tip,Tip)
1221partitionWithKey p (Bin _ kx x l r)
1222  | p kx x    = (join kx x l1 r1,merge l2 r2)
1223  | otherwise = (merge l1 r1,join kx x l2 r2)
1224  where
1225    (l1,l2) = partitionWithKey p l
1226    (r1,r2) = partitionWithKey p r
1227
1228-- | /O(n)/. Map values and collect the 'Just' results.
1229--
1230-- > let f x = if x == "a" then Just "new a" else Nothing
1231-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
1232
1233mapMaybe :: Ord k => (a -> Maybe b) -> Map k a -> Map k b
1234mapMaybe f m
1235  = mapWithMaybeKey (\_ x -> f x) m
1236
1237-- | /O(n)/. Map keys\/values and collect the 'Just' results.
1238--
1239-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
1240-- > mapWithMaybeKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
1241
1242mapWithMaybeKey :: Ord k => (k -> a -> Maybe b) -> Map k a -> Map k b
1243mapWithMaybeKey _ Tip = Tip
1244mapWithMaybeKey f (Bin _ kx x l r) = case f kx x of
1245  Just y  -> join kx y (mapWithMaybeKey f l) (mapWithMaybeKey f r)
1246  Nothing -> merge (mapWithMaybeKey f l) (mapWithMaybeKey f r)
1247
1248-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
1249--
1250-- > let f a = if a < "c" then Left a else Right a
1251-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1252-- >     == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
1253-- >
1254-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1255-- >     == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1256
1257mapEither :: Ord k => (a -> Either b c) -> Map k a -> (Map k b, Map k c)
1258mapEither f m
1259  = mapEitherWithKey (\_ x -> f x) m
1260
1261-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
1262--
1263-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
1264-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1265-- >     == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
1266-- >
1267-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
1268-- >     == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
1269
1270mapEitherWithKey :: Ord k =>
1271  (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
1272mapEitherWithKey _ Tip = (Tip, Tip)
1273mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
1274  Left y  -> (join kx y l1 r1, merge l2 r2)
1275  Right z -> (merge l1 r1, join kx z l2 r2)
1276  where
1277    (l1,l2) = mapEitherWithKey f l
1278    (r1,r2) = mapEitherWithKey f r
1279
1280{--------------------------------------------------------------------
1281  Mapping
1282--------------------------------------------------------------------}
1283-- | /O(n)/. Map a function over all values in the map.
1284--
1285-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
1286
1287map :: (a -> b) -> Map k a -> Map k b
1288map f m
1289  = mapWithKey (\_ x -> f x) m
1290
1291-- | /O(n)/. Map a function over all values in the map.
1292--
1293-- > let f key x = (show key) ++ ":" ++ x
1294-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
1295
1296mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
1297mapWithKey _ Tip = Tip
1298mapWithKey f (Bin sx kx x l r) 
1299  = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
1300
1301-- | /O(n)/. The function 'mapAccum' threads an accumulating
1302-- argument through the map in ascending order of keys.
1303--
1304-- > let f a b = (a ++ b, b ++ "X")
1305-- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
1306
1307mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1308mapAccum f a m
1309  = mapAccumWithKey (\a' _ x' -> f a' x') a m
1310
1311-- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1312-- argument through the map in ascending order of keys.
1313--
1314-- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1315-- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1316
1317mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1318mapAccumWithKey f a t
1319  = mapAccumL f a t
1320
1321-- | /O(n)/. The function 'mapAccumL' threads an accumulating
1322-- argument throught the map in ascending order of keys.
1323mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1324mapAccumL f a t
1325  = case t of
1326      Tip -> (a,Tip)
1327      Bin sx kx x l r
1328          -> let (a1,l') = mapAccumL f a l
1329                 (a2,x') = f a1 kx x
1330                 (a3,r') = mapAccumL f a2 r
1331             in (a3,Bin sx kx x' l' r')
1332
1333-- | /O(n)/. The function 'mapAccumR' threads an accumulating
1334-- argument through the map in descending order of keys.
1335mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1336mapAccumRWithKey f a t
1337  = case t of
1338      Tip -> (a,Tip)
1339      Bin sx kx x l r
1340          -> let (a1,r') = mapAccumRWithKey f a r
1341                 (a2,x') = f a1 kx x
1342                 (a3,l') = mapAccumRWithKey f a2 l
1343             in (a3,Bin sx kx x' l' r')
1344
1345-- | /O(n*log n)/.
1346-- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
1347--
1348-- The size of the result may be smaller if @f@ maps two or more distinct
1349-- keys to the same new key.  In this case the value at the smallest of
1350-- these keys is retained.
1351--
1352-- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")])                        == fromList [(4, "b"), (6, "a")]
1353-- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
1354-- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
1355
1356mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
1357mapKeys = mapKeysWith (\x _ -> x)
1358
1359-- | /O(n*log n)/.
1360-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1361--
1362-- The size of the result may be smaller if @f@ maps two or more distinct
1363-- keys to the same new key.  In this case the associated values will be
1364-- combined using @c@.
1365--
1366-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1367-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1368
1369mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1370mapKeysWith c f = fromListWith c . List.map fFirst . toList
1371    where fFirst (x,y) = (f x, y)
1372
1373
1374-- | /O(n)/.
1375-- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
1376-- is strictly monotonic.
1377-- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
1378-- /The precondition is not checked./
1379-- Semi-formally, we have:
1380--
1381-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
1382-- >                     ==> mapKeysMonotonic f s == mapKeys f s
1383-- >     where ls = keys s
1384--
1385-- This means that @f@ maps distinct original keys to distinct resulting keys.
1386-- This function has better performance than 'mapKeys'.
1387--
1388-- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
1389-- > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
1390-- > valid (mapKeysMonotonic (\ _ -> 1)     (fromList [(5,"a"), (3,"b")])) == False
1391
1392mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
1393mapKeysMonotonic _ Tip = Tip
1394mapKeysMonotonic f (Bin sz k x l r) =
1395    Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
1396
1397{--------------------------------------------------------------------
1398  Folds 
1399--------------------------------------------------------------------}
1400
1401-- | /O(n)/. Fold the values in the map, such that
1402-- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
1403-- For example,
1404--
1405-- > elems map = fold (:) [] map
1406--
1407-- > let f a len = len + (length a)
1408-- > fold f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
1409
1410fold :: (a -> b -> b) -> b -> Map k a -> b
1411fold f z m
1412  = foldWithKey (\_ x' z' -> f x' z') z m
1413
1414-- | /O(n)/. Fold the keys and values in the map, such that
1415-- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
1416-- For example,
1417--
1418-- > keys map = foldWithKey (\k x ks -> k:ks) [] map
1419--
1420-- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
1421-- > foldWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
1422--
1423-- This is identical to 'foldrWithKey', and you should use that one instead of
1424-- this one.  This name is kept for backward compatibility.
1425
1426foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
1427foldWithKey f z t
1428  = foldrWithKey f z t
1429
1430{-
1431XXX unused code
1432
1433-- | /O(n)/. In-order fold.
1434foldi :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
1435foldi _ z Tip               = z
1436foldi f z (Bin _ kx x l r)  = f kx x (foldi f z l) (foldi f z r)
1437-}
1438
1439-- | /O(n)/. Post-order fold.  The function will be applied from the lowest
1440-- value to the highest.
1441foldrWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
1442foldrWithKey _ z Tip              = z
1443foldrWithKey f z (Bin _ kx x l r) =
1444    foldrWithKey f (f kx x (foldrWithKey f z r)) l
1445
1446
1447-- | /O(n)/. Pre-order fold.  The function will be applied from the highest
1448-- value to the lowest.
1449foldlWithKey :: (b -> k -> a -> b) -> b -> Map k a -> b
1450foldlWithKey _ z Tip              = z
1451foldlWithKey f z (Bin _ kx x l r) =
1452    foldlWithKey f (f (foldlWithKey f z l) kx x) r
1453
1454{--------------------------------------------------------------------
1455  List variations
1456--------------------------------------------------------------------}
1457-- | /O(n)/.
1458-- Return all elements of the map in the ascending order of their keys.
1459--
1460-- > elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
1461-- > elems empty == []
1462
1463elems :: Map k a -> [a]
1464elems m
1465  = [x | (_,x) <- assocs m]
1466
1467-- | /O(n)/. Return all keys of the map in ascending order.
1468--
1469-- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
1470-- > keys empty == []
1471
1472keys  :: Map k a -> [k]
1473keys m
1474  = [k | (k,_) <- assocs m]
1475
1476-- | /O(n)/. The set of all keys of the map.
1477--
1478-- > keysSet (fromList [(5,"a"), (3,"b")]) == Data.Set.fromList [3,5]
1479-- > keysSet empty == Data.Set.empty
1480
1481keysSet :: Map k a -> Set.Set k
1482keysSet m = Set.fromDistinctAscList (keys m)
1483
1484-- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
1485--
1486-- > assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1487-- > assocs empty == []
1488
1489assocs :: Map k a -> [(k,a)]
1490assocs m
1491  = toList m
1492
1493{--------------------------------------------------------------------
1494  Lists
1495  use [foldlStrict] to reduce demand on the control-stack
1496--------------------------------------------------------------------}
1497-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1498-- If the list contains more than one value for the same key, the last value
1499-- for the key is retained.
1500--
1501-- > fromList [] == empty
1502-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1503-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1504
1505fromList :: Ord k => [(k,a)] -> Map k a
1506fromList xs       
1507  = foldlStrict ins empty xs
1508  where
1509    ins t (k,x) = insert k x t
1510
1511-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1512--
1513-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1514-- > fromListWith (++) [] == empty
1515
1516fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1517fromListWith f xs
1518  = fromListWithKey (\_ x y -> f x y) xs
1519
1520-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1521--
1522-- > let f k a1 a2 = (show k) ++ a1 ++ a2
1523-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1524-- > fromListWithKey f [] == empty
1525
1526fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1527fromListWithKey f xs
1528  = foldlStrict ins empty xs
1529  where
1530    ins t (k,x) = insertWithKey f k x t
1531
1532-- | /O(n)/. Convert to a list of key\/value pairs.
1533--
1534-- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1535-- > toList empty == []
1536
1537toList :: Map k a -> [(k,a)]
1538toList t      = toAscList t
1539
1540-- | /O(n)/. Convert to an ascending list.
1541--
1542-- > toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
1543
1544toAscList :: Map k a -> [(k,a)]
1545toAscList t   = foldrWithKey (\k x xs -> (k,x):xs) [] t
1546
1547-- | /O(n)/. Convert to a descending list.
1548toDescList :: Map k a -> [(k,a)]
1549toDescList t  = foldlWithKey (\xs k x -> (k,x):xs) [] t
1550
1551{--------------------------------------------------------------------
1552  Building trees from ascending/descending lists can be done in linear time.
1553 
1554  Note that if [xs] is ascending that:
1555    fromAscList xs       == fromList xs
1556    fromAscListWith f xs == fromListWith f xs
1557--------------------------------------------------------------------}
1558-- | /O(n)/. Build a map from an ascending list in linear time.
1559-- /The precondition (input list is ascending) is not checked./
1560--
1561-- > fromAscList [(3,"b"), (5,"a")]          == fromList [(3, "b"), (5, "a")]
1562-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1563-- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1564-- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1565
1566fromAscList :: Eq k => [(k,a)] -> Map k a
1567fromAscList xs
1568  = fromAscListWithKey (\_ x _ -> x) xs
1569
1570-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1571-- /The precondition (input list is ascending) is not checked./
1572--
1573-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1574-- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1575-- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1576
1577fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1578fromAscListWith f xs
1579  = fromAscListWithKey (\_ x y -> f x y) xs
1580
1581-- | /O(n)/. Build a map from an ascending list in linear time with a
1582-- combining function for equal keys.
1583-- /The precondition (input list is ascending) is not checked./
1584--
1585-- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1586-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1587-- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1588-- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1589
1590fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1591fromAscListWithKey f xs
1592  = fromDistinctAscList (combineEq f xs)
1593  where
1594  -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1595  combineEq _ xs'
1596    = case xs' of
1597        []     -> []
1598        [x]    -> [x]
1599        (x:xx) -> combineEq' x xx
1600
1601  combineEq' z [] = [z]
1602  combineEq' z@(kz,zz) (x@(kx,xx):xs')
1603    | kx==kz    = let yy = f kx xx zz in combineEq' (kx,yy) xs'
1604    | otherwise = z:combineEq' x xs'
1605
1606
1607-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1608-- /The precondition is not checked./
1609--
1610-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1611-- > valid (fromDistinctAscList [(3,"b"), (5,"a")])          == True
1612-- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1613
1614fromDistinctAscList :: [(k,a)] -> Map k a
1615fromDistinctAscList xs
1616  = build const (length xs) xs
1617  where
1618    -- 1) use continutations so that we use heap space instead of stack space.
1619    -- 2) special case for n==5 to build bushier trees.
1620    build c 0 xs'  = c Tip xs'
1621    build c 5 xs'  = case xs' of
1622                       ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx) 
1623                            -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1624                       _ -> error "fromDistinctAscList build"
1625    build c n xs'  = seq nr $ build (buildR nr c) nl xs'
1626                   where
1627                     nl = n `div` 2
1628                     nr = n - nl - 1
1629
1630    buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
1631    buildR _ _ _ []         = error "fromDistinctAscList buildR []"
1632    buildB l k x c r zs     = c (bin k x l r) zs
1633                     
1634
1635
1636{--------------------------------------------------------------------
1637  Utility functions that return sub-ranges of the original
1638  tree. Some functions take a comparison function as argument to
1639  allow comparisons against infinite values. A function [cmplo k]
1640  should be read as [compare lo k].
1641
1642  [trim cmplo cmphi t]  A tree that is either empty or where [cmplo k == LT]
1643                        and [cmphi k == GT] for the key [k] of the root.
1644  [filterGt cmp t]      A tree where for all keys [k]. [cmp k == LT]
1645  [filterLt cmp t]      A tree where for all keys [k]. [cmp k == GT]
1646
1647  [split k t]           Returns two trees [l] and [r] where all keys
1648                        in [l] are <[k] and all keys in [r] are >[k].
1649  [splitLookup k t]     Just like [split] but also returns whether [k]
1650                        was found in the tree.
1651--------------------------------------------------------------------}
1652
1653{--------------------------------------------------------------------
1654  [trim lo hi t] trims away all subtrees that surely contain no
1655  values between the range [lo] to [hi]. The returned tree is either
1656  empty or the key of the root is between @lo@ and @hi@.
1657--------------------------------------------------------------------}
1658trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
1659trim _     _     Tip = Tip
1660trim cmplo cmphi t@(Bin _ kx _ l r)
1661  = case cmplo kx of
1662      LT -> case cmphi kx of
1663              GT -> t
1664              _  -> trim cmplo cmphi l
1665      _  -> trim cmplo cmphi r
1666             
1667trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe (k,a), Map k a)
1668trimLookupLo _  _     Tip = (Nothing,Tip)
1669trimLookupLo lo cmphi t@(Bin _ kx x l r)
1670  = case compare lo kx of
1671      LT -> case cmphi kx of
1672              GT -> (lookupAssoc lo t, t)
1673              _  -> trimLookupLo lo cmphi l
1674      GT -> trimLookupLo lo cmphi r
1675      EQ -> (Just (kx,x),trim (compare lo) cmphi r)
1676
1677
1678{--------------------------------------------------------------------
1679  [filterGt k t] filter all keys >[k] from tree [t]
1680  [filterLt k t] filter all keys <[k] from tree [t]
1681--------------------------------------------------------------------}
1682filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1683filterGt _   Tip = Tip
1684filterGt cmp (Bin _ kx x l r)
1685  = case cmp kx of
1686      LT -> join kx x (filterGt cmp l) r
1687      GT -> filterGt cmp r
1688      EQ -> r
1689     
1690filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1691filterLt _   Tip = Tip
1692filterLt cmp (Bin _ kx x l r)
1693  = case cmp kx of
1694      LT -> filterLt cmp l
1695      GT -> join kx x l (filterLt cmp r)
1696      EQ -> l
1697
1698{--------------------------------------------------------------------
1699  Split
1700--------------------------------------------------------------------}
1701-- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
1702-- the keys in @map1@ are smaller than @k@ and the keys in @map2@ larger than @k@.
1703-- Any key equal to @k@ is found in neither @map1@ nor @map2@.
1704--
1705-- > split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")])
1706-- > split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a")
1707-- > split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
1708-- > split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty)
1709-- > split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty)
1710
1711split :: Ord k => k -> Map k a -> (Map k a,Map k a)
1712split _ Tip = (Tip,Tip)
1713split k (Bin _ kx x l r)
1714  = case compare k kx of
1715      LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
1716      GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
1717      EQ -> (l,r)
1718
1719-- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
1720-- like 'split' but also returns @'lookup' k map@.
1721--
1722-- > splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")])
1723-- > splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a")
1724-- > splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a")
1725-- > splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty)
1726-- > splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)
1727
1728splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
1729splitLookup _ Tip = (Tip,Nothing,Tip)
1730splitLookup k (Bin _ kx x l r)
1731  = case compare k kx of
1732      LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
1733      GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
1734      EQ -> (l,Just x,r)
1735
1736-- | /O(log n)/.
1737splitLookupWithKey :: Ord k => k -> Map k a -> (Map k a,Maybe (k,a),Map k a)
1738splitLookupWithKey _ Tip = (Tip,Nothing,Tip)
1739splitLookupWithKey k (Bin _ kx x l r)
1740  = case compare k kx of
1741      LT -> let (lt,z,gt) = splitLookupWithKey k l in (lt,z,join kx x gt r)
1742      GT -> let (lt,z,gt) = splitLookupWithKey k r in (join kx x l lt,z,gt)
1743      EQ -> (l,Just (kx, x),r)
1744
1745{-
1746XXX unused code
1747
1748-- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1749-- element was found in the original set.
1750splitMember :: Ord k => k -> Map k a -> (Map k a,Bool,Map k a)
1751splitMember x t = let (l,m,r) = splitLookup x t in
1752     (l,maybe False (const True) m,r)
1753-}
1754
1755{--------------------------------------------------------------------
1756  Utility functions that maintain the balance properties of the tree.
1757  All constructors assume that all values in [l] < [k] and all values
1758  in [r] > [k], and that [l] and [r] are valid trees.
1759 
1760  In order of sophistication:
1761    [Bin sz k x l r]  The type constructor.
1762    [bin k x l r]     Maintains the correct size, assumes that both [l]
1763                      and [r] are balanced with respect to each other.
1764    [balance k x l r] Restores the balance and size.
1765                      Assumes that the original tree was balanced and
1766                      that [l] or [r] has changed by at most one element.
1767    [join k x l r]    Restores balance and size.
1768
1769  Furthermore, we can construct a new tree from two trees. Both operations
1770  assume that all values in [l] < all values in [r] and that [l] and [r]
1771  are valid:
1772    [glue l r]        Glues [l] and [r] together. Assumes that [l] and
1773                      [r] are already balanced with respect to each other.
1774    [merge l r]       Merges two trees and restores balance.
1775
1776  Note: in contrast to Adam's paper, we use (<=) comparisons instead
1777  of (<) comparisons in [join], [merge] and [balance].
1778  Quickcheck (on [difference]) showed that this was necessary in order
1779  to maintain the invariants. It is quite unsatisfactory that I haven't
1780  been able to find out why this is actually the case! Fortunately, it
1781  doesn't hurt to be a bit more conservative.
1782--------------------------------------------------------------------}
1783
1784{--------------------------------------------------------------------
1785  Join
1786--------------------------------------------------------------------}
1787join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
1788join kx x Tip r  = insertMin kx x r
1789join kx x l Tip  = insertMax kx x l
1790join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
1791  | delta*sizeL <= sizeR  = balance kz z (join kx x l lz) rz
1792  | delta*sizeR <= sizeL  = balance ky y ly (join kx x ry r)
1793  | otherwise             = bin kx x l r
1794
1795
1796-- insertMin and insertMax don't perform potentially expensive comparisons.
1797insertMax,insertMin :: k -> a -> Map k a -> Map k a
1798insertMax kx x t
1799  = case t of
1800      Tip -> singleton kx x
1801      Bin _ ky y l r
1802          -> balance ky y l (insertMax kx x r)
1803             
1804insertMin kx x t
1805  = case t of
1806      Tip -> singleton kx x
1807      Bin _ ky y l r
1808          -> balance ky y (insertMin kx x l) r
1809             
1810{--------------------------------------------------------------------
1811  [merge l r]: merges two trees.
1812--------------------------------------------------------------------}
1813merge :: Map k a -> Map k a -> Map k a
1814merge Tip r   = r
1815merge l Tip   = l
1816merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
1817  | delta*sizeL <= sizeR = balance ky y (merge l ly) ry
1818  | delta*sizeR <= sizeL = balance kx x lx (merge rx r)
1819  | otherwise            = glue l r
1820
1821{--------------------------------------------------------------------
1822  [glue l r]: glues two trees together.
1823  Assumes that [l] and [r] are already balanced with respect to each other.
1824--------------------------------------------------------------------}
1825glue :: Map k a -> Map k a -> Map k a
1826glue Tip r = r
1827glue l Tip = l
1828glue l r   
1829  | size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
1830  | otherwise       = let ((km,m),r') = deleteFindMin r in balance km m l r'
1831
1832
1833-- | /O(log n)/. Delete and find the minimal element.
1834--
1835-- > deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")])
1836-- > deleteFindMin                                            Error: can not return the minimal element of an empty map
1837
1838deleteFindMin :: Map k a -> ((k,a),Map k a)
1839deleteFindMin t
1840  = case t of
1841      Bin _ k x Tip r -> ((k,x),r)
1842      Bin _ k x l r   -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
1843      Tip             -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
1844
1845-- | /O(log n)/. Delete and find the maximal element.
1846--
1847-- > deleteFindMax (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((10,"c"), fromList [(3,"b"), (5,"a")])
1848-- > deleteFindMax empty                                      Error: can not return the maximal element of an empty map
1849
1850deleteFindMax :: Map k a -> ((k,a),Map k a)
1851deleteFindMax t
1852  = case t of
1853      Bin _ k x l Tip -> ((k,x),l)
1854      Bin _ k x l r   -> let (km,r') = deleteFindMax r in (km,balance k x l r')
1855      Tip             -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
1856
1857
1858{--------------------------------------------------------------------
1859  [balance l x r] balances two trees with value x.
1860  The sizes of the trees should balance after decreasing the
1861  size of one of them. (a rotation).
1862
1863  [delta] is the maximal relative difference between the sizes of
1864          two trees, it corresponds with the [w] in Adams' paper.
1865  [ratio] is the ratio between an outer and inner sibling of the
1866          heavier subtree in an unbalanced setting. It determines
1867          whether a double or single rotation should be performed
1868          to restore balance. It is correspondes with the inverse
1869          of $\alpha$ in Adam's article.
1870
1871  Note that:
1872  - [delta] should be larger than 4.646 with a [ratio] of 2.
1873  - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1874 
1875  - A lower [delta] leads to a more 'perfectly' balanced tree.
1876  - A higher [delta] performs less rebalancing.
1877
1878  - Balancing is automatic for random data and a balancing
1879    scheme is only necessary to avoid pathological worst cases.
1880    Almost any choice will do, and in practice, a rather large
1881    [delta] may perform better than smaller one.
1882
1883  Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
1884  to decide whether a single or double rotation is needed. Allthough
1885  he actually proves that this ratio is needed to maintain the
1886  invariants, his implementation uses an invalid ratio of [1].
1887--------------------------------------------------------------------}
1888delta,ratio :: Int
1889delta = 5
1890ratio = 2
1891
1892balance :: k -> a -> Map k a -> Map k a -> Map k a
1893balance k x l r
1894  | sizeL + sizeR <= 1    = Bin sizeX k x l r
1895  | sizeR >= delta*sizeL  = rotateL k x l r
1896  | sizeL >= delta*sizeR  = rotateR k x l r
1897  | otherwise             = Bin sizeX k x l r
1898  where
1899    sizeL = size l
1900    sizeR = size r
1901    sizeX = sizeL + sizeR + 1
1902
1903-- rotate
1904rotateL :: a -> b -> Map a b -> Map a b -> Map a b
1905rotateL k x l r@(Bin _ _ _ ly ry)
1906  | size ly < ratio*size ry = singleL k x l r
1907  | otherwise               = doubleL k x l r
1908rotateL _ _ _ Tip = error "rotateL Tip"
1909
1910rotateR :: a -> b -> Map a b -> Map a b -> Map a b
1911rotateR k x l@(Bin _ _ _ ly ry) r
1912  | size ry < ratio*size ly = singleR k x l r
1913  | otherwise               = doubleR k x l r
1914rotateR _ _ Tip _ = error "rotateR Tip"
1915
1916-- basic rotations
1917singleL, singleR :: a -> b -> Map a b -> Map a b -> Map a b
1918singleL k1 x1 t1 (Bin _ k2 x2 t2 t3)  = bin k2 x2 (bin k1 x1 t1 t2) t3
1919singleL _ _ _ Tip = error "singleL Tip"
1920singleR k1 x1 (Bin _ k2 x2 t1 t2) t3  = bin k2 x2 t1 (bin k1 x1 t2 t3)
1921singleR _ _ Tip _ = error "singleR Tip"
1922
1923doubleL, doubleR :: a -> b -> Map a b -> Map a b -> Map a b
1924doubleL 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)
1925doubleL _ _ _ _ = error "doubleL"
1926doubleR 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)
1927doubleR _ _ _ _ = error "doubleR"
1928
1929
1930{--------------------------------------------------------------------
1931  The bin constructor maintains the size of the tree
1932--------------------------------------------------------------------}
1933bin :: k -> a -> Map k a -> Map k a -> Map k a
1934bin k x l r
1935  = Bin (size l + size r + 1) k x l r
1936
1937
1938{--------------------------------------------------------------------
1939  Eq converts the tree to a list. In a lazy setting, this
1940  actually seems one of the faster methods to compare two trees
1941  and it is certainly the simplest :-)
1942--------------------------------------------------------------------}
1943instance (Eq k,Eq a) => Eq (Map k a) where
1944  t1 == t2  = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1945
1946{--------------------------------------------------------------------
1947  Ord
1948--------------------------------------------------------------------}
1949
1950instance (Ord k, Ord v) => Ord (Map k v) where
1951    compare m1 m2 = compare (toAscList m1) (toAscList m2)
1952
1953{--------------------------------------------------------------------
1954  Functor
1955--------------------------------------------------------------------}
1956instance Functor (Map k) where
1957  fmap f m  = map f m
1958
1959instance Traversable (Map k) where
1960  traverse _ Tip = pure Tip
1961  traverse f (Bin s k v l r)
1962    = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
1963
1964instance Foldable (Map k) where
1965  foldMap _f Tip = mempty
1966  foldMap f (Bin _s _k v l r)
1967    = foldMap f l `mappend` f v `mappend` foldMap f r
1968
1969{--------------------------------------------------------------------
1970  Read
1971--------------------------------------------------------------------}
1972instance (Ord k, Read k, Read e) => Read (Map k e) where
1973#ifdef __GLASGOW_HASKELL__
1974  readPrec = parens $ prec 10 $ do
1975    Ident "fromList" <- lexP
1976    xs <- readPrec
1977    return (fromList xs)
1978
1979  readListPrec = readListPrecDefault
1980#else
1981  readsPrec p = readParen (p > 10) $ \ r -> do
1982    ("fromList",s) <- lex r
1983    (xs,t) <- reads s
1984    return (fromList xs,t)
1985#endif
1986
1987{-
1988XXX unused code
1989
1990-- parses a pair of things with the syntax a:=b
1991readPair :: (Read a, Read b) => ReadS (a,b)
1992readPair s = do (a, ct1)    <- reads s
1993                (":=", ct2) <- lex ct1
1994                (b, ct3)    <- reads ct2
1995                return ((a,b), ct3)
1996-}
1997
1998{--------------------------------------------------------------------
1999  Show
2000--------------------------------------------------------------------}
2001instance (Show k, Show a) => Show (Map k a) where
2002  showsPrec d m  = showParen (d > 10) $
2003    showString "fromList " . shows (toList m)
2004
2005{-
2006XXX unused code
2007
2008showMap :: (Show k,Show a) => [(k,a)] -> ShowS
2009showMap []     
2010  = showString "{}"
2011showMap (x:xs)
2012  = showChar '{' . showElem x . showTail xs
2013  where
2014    showTail []     = showChar '}'
2015    showTail (x':xs') = showString ", " . showElem x' . showTail xs'
2016   
2017    showElem (k,x')  = shows k . showString " := " . shows x'
2018-}
2019
2020-- | /O(n)/. Show the tree that implements the map. The tree is shown
2021-- in a compressed, hanging format. See 'showTreeWith'.
2022showTree :: (Show k,Show a) => Map k a -> String
2023showTree m
2024  = showTreeWith showElem True False m
2025  where
2026    showElem k x  = show k ++ ":=" ++ show x
2027
2028
2029{- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
2030 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
2031 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
2032 @wide@ is 'True', an extra wide version is shown.
2033
2034>  Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
2035>  Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
2036>  (4,())
2037>  +--(2,())
2038>  |  +--(1,())
2039>  |  +--(3,())
2040>  +--(5,())
2041>
2042>  Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
2043>  (4,())
2044>  |
2045>  +--(2,())
2046>  |  |
2047>  |  +--(1,())
2048>  |  |
2049>  |  +--(3,())
2050>  |
2051>  +--(5,())
2052>
2053>  Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
2054>  +--(5,())
2055>  |
2056>  (4,())
2057>  |
2058>  |  +--(3,())
2059>  |  |
2060>  +--(2,())
2061>     |
2062>     +--(1,())
2063
2064-}
2065showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
2066showTreeWith showelem hang wide t
2067  | hang      = (showsTreeHang showelem wide [] t) ""
2068  | otherwise = (showsTree showelem wide [] [] t) ""
2069
2070showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
2071showsTree showelem wide lbars rbars t
2072  = case t of
2073      Tip -> showsBars lbars . showString "|\n"
2074      Bin _ kx x Tip Tip
2075          -> showsBars lbars . showString (showelem kx x) . showString "\n" 
2076      Bin _ kx x l r
2077          -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
2078             showWide wide rbars .
2079             showsBars lbars . showString (showelem kx x) . showString "\n" .
2080             showWide wide lbars .
2081             showsTree showelem wide (withEmpty lbars) (withBar lbars) l
2082
2083showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
2084showsTreeHang showelem wide bars t
2085  = case t of
2086      Tip -> showsBars bars . showString "|\n" 
2087      Bin _ kx x Tip Tip
2088          -> showsBars bars . showString (showelem kx x) . showString "\n" 
2089      Bin _ kx x l r
2090          -> showsBars bars . showString (showelem kx x) . showString "\n" . 
2091             showWide wide bars .
2092             showsTreeHang showelem wide (withBar bars) l .
2093             showWide wide bars .
2094             showsTreeHang showelem wide (withEmpty bars) r
2095
2096showWide :: Bool -> [String] -> String -> String
2097showWide wide bars
2098  | wide      = showString (concat (reverse bars)) . showString "|\n" 
2099  | otherwise = id
2100
2101showsBars :: [String] -> ShowS
2102showsBars bars
2103  = case bars of
2104      [] -> id
2105      _  -> showString (concat (reverse (tail bars))) . showString node
2106
2107node :: String
2108node           = "+--"
2109
2110withBar, withEmpty :: [String] -> [String]
2111withBar bars   = "|  ":bars
2112withEmpty bars = "   ":bars
2113
2114{--------------------------------------------------------------------
2115  Typeable
2116--------------------------------------------------------------------}
2117
2118#include "Typeable.h"
2119INSTANCE_TYPEABLE2(Map,mapTc,"Map")
2120
2121{--------------------------------------------------------------------
2122  Assertions
2123--------------------------------------------------------------------}
2124-- | /O(n)/. Test if the internal map structure is valid.
2125--
2126-- > valid (fromAscList [(3,"b"), (5,"a")]) == True
2127-- > valid (fromAscList [(5,"a"), (3,"b")]) == False
2128
2129valid :: Ord k => Map k a -> Bool
2130valid t
2131  = balanced t && ordered t && validsize t
2132
2133ordered :: Ord a => Map a b -> Bool
2134ordered t
2135  = bounded (const True) (const True) t
2136  where
2137    bounded lo hi t'
2138      = case t' of
2139          Tip              -> True
2140          Bin _ kx _ l r  -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
2141
2142-- | Exported only for "Debug.QuickCheck"
2143balanced :: Map k a -> Bool
2144balanced t
2145  = case t of
2146      Tip            -> True
2147      Bin _ _ _ l r  -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
2148                        balanced l && balanced r
2149
2150validsize :: Map a b -> Bool
2151validsize t
2152  = (realsize t == Just (size t))
2153  where
2154    realsize t'
2155      = case t' of
2156          Tip            -> Just 0
2157          Bin sz _ _ l r -> case (realsize l,realsize r) of
2158                            (Just n,Just m)  | n+m+1 == sz  -> Just sz
2159                            _                               -> Nothing
2160
2161{--------------------------------------------------------------------
2162  Utilities
2163--------------------------------------------------------------------}
2164foldlStrict :: (a -> b -> a) -> a -> [b] -> a
2165foldlStrict f z xs
2166  = case xs of
2167      []     -> z
2168      (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
2169
2170unionWithMaybe :: Ord k => (a -> a -> Maybe a) -> Map k a -> Map k a -> Map k a
2171unionWithMaybe f m1 m2
2172  = unionWithMaybeKey (\_ x y -> f x y) m1 m2
2173
2174-- | /O(n+m)/.
2175-- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
2176-- Hedge-union is more efficient on (bigset \``union`\` smallset).
2177--
2178-- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
2179-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
2180
2181unionWithMaybeKey :: Ord k => (k -> a -> a -> Maybe a) -> Map k a -> Map k a -> Map k a
2182unionWithMaybeKey _ Tip t2  = t2
2183unionWithMaybeKey _ t1 Tip  = t1
2184unionWithMaybeKey f t1 t2 = hedgeUnionWithMaybeKey f (const LT) (const GT) t1 t2
2185
2186
2187hedgeUnionWithMaybeKey :: Ord a
2188                  => (a -> b -> b -> Maybe b)
2189                  -> (a -> Ordering) -> (a -> Ordering)
2190                  -> Map a b -> Map a b
2191                  -> Map a b
2192hedgeUnionWithMaybeKey _ _     _     t1 Tip
2193  = t1
2194hedgeUnionWithMaybeKey _ cmplo cmphi Tip (Bin _ kx x l r)
2195  = join kx x (filterGt cmplo l) (filterLt cmphi r)
2196hedgeUnionWithMaybeKey f cmplo cmphi (Bin _ kx x l r) t2
2197  = case newx of
2198     Nothing -> merge (hedgeUnionWithMaybeKey f cmplo cmpkx l lt) 
2199                      (hedgeUnionWithMaybeKey f cmpkx cmphi r gt)
2200     (Just nx) -> join kx nx (hedgeUnionWithMaybeKey f cmplo cmpkx l lt) 
2201                             (hedgeUnionWithMaybeKey f cmpkx cmphi r gt)
2202  where
2203    cmpkx k     = compare kx k
2204    lt          = trim cmplo cmpkx t2
2205    (found,gt)  = trimLookupLo kx cmphi t2
2206    newx        = case found of
2207                    Nothing -> Just x
2208                    Just (_,y) -> f kx x y