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