Ticket #1611: Map.hs

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