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