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