6c795aac453bcfcb725fbf9cbfab8659d860a0a2
[haskell-directory.git] / Data / IntMap.hs
1 {-# OPTIONS -cpp -fglasgow-exts -fno-bang-patterns #-} 
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Data.IntMap
5 -- Copyright   :  (c) Daan Leijen 2002
6 -- License     :  BSD-style
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- An efficient implementation of maps from integer keys to values.
12 --
13 -- Since many function names (but not the type name) clash with
14 -- "Prelude" names, this module is usually imported @qualified@, e.g.
15 --
16 -- >  import Data.IntMap (IntMap)
17 -- >  import qualified Data.IntMap as IntMap
18 --
19 -- The implementation is based on /big-endian patricia trees/.  This data
20 -- structure performs especially well on binary operations like 'union'
21 -- and 'intersection'.  However, my benchmarks show that it is also
22 -- (much) faster on insertions and deletions when compared to a generic
23 -- size-balanced map implementation (see "Data.Map" and "Data.FiniteMap").
24 --
25 --    * Chris Okasaki and Andy Gill,  \"/Fast Mergeable Integer Maps/\",
26 --      Workshop on ML, September 1998, pages 77-86,
27 --      <http://www.cse.ogi.edu/~andy/pub/finite.htm>
28 --
29 --    * D.R. Morrison, \"/PATRICIA -- Practical Algorithm To Retrieve
30 --      Information Coded In Alphanumeric/\", Journal of the ACM, 15(4),
31 --      October 1968, pages 514-534.
32 --
33 -- Many operations have a worst-case complexity of /O(min(n,W))/.
34 -- This means that the operation can become linear in the number of
35 -- elements with a maximum of /W/ -- the number of bits in an 'Int'
36 -- (32 or 64).
37 -----------------------------------------------------------------------------
38
39 module Data.IntMap  ( 
40             -- * Map type
41               IntMap, Key          -- instance Eq,Show
42
43             -- * Operators
44             , (!), (\\)
45
46             -- * Query
47             , null
48             , size
49             , member
50             , notMember
51             , lookup
52             , findWithDefault
53             
54             -- * Construction
55             , empty
56             , singleton
57
58             -- ** Insertion
59             , insert
60             , insertWith, insertWithKey, insertLookupWithKey
61             
62             -- ** Delete\/Update
63             , delete
64             , adjust
65             , adjustWithKey
66             , update
67             , updateWithKey
68             , updateLookupWithKey
69             , alter
70   
71             -- * Combine
72
73             -- ** Union
74             , union         
75             , unionWith          
76             , unionWithKey
77             , unions
78             , unionsWith
79
80             -- ** Difference
81             , difference
82             , differenceWith
83             , differenceWithKey
84             
85             -- ** Intersection
86             , intersection           
87             , intersectionWith
88             , intersectionWithKey
89
90             -- * Traversal
91             -- ** Map
92             , map
93             , mapWithKey
94             , mapAccum
95             , mapAccumWithKey
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             , mapMaybe
127             , mapMaybeWithKey
128             , mapEither
129             , mapEitherWithKey
130
131             , split         
132             , splitLookup   
133
134             -- * Submap
135             , isSubmapOf, isSubmapOfBy
136             , isProperSubmapOf, isProperSubmapOfBy
137             
138             -- * Min\/Max
139
140             , maxView
141             , minView
142             , findMin   
143             , findMax
144             , deleteMin
145             , deleteMax
146             , deleteFindMin
147             , deleteFindMax
148             , updateMin
149             , updateMax
150             , updateMinWithKey
151             , updateMaxWithKey 
152             , minViewWithKey
153             , maxViewWithKey
154
155             -- * Debugging
156             , showTree
157             , showTreeWith
158             ) where
159
160
161 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
162 import Data.Bits 
163 import qualified Data.IntSet as IntSet
164 import Data.Monoid (Monoid(..))
165 import Data.Typeable
166 import Data.Foldable (Foldable(foldMap))
167 import Control.Monad ( liftM )
168 {-
169 -- just for testing
170 import qualified Prelude
171 import Debug.QuickCheck 
172 import List (nub,sort)
173 import qualified List
174 -}  
175
176 #if __GLASGOW_HASKELL__
177 import Text.Read
178 import Data.Generics.Basics (Data(..), mkNorepType)
179 import Data.Generics.Instances ()
180 #endif
181
182 #if __GLASGOW_HASKELL__ >= 503
183 import GHC.Exts ( Word(..), Int(..), shiftRL# )
184 #elif __GLASGOW_HASKELL__
185 import Word
186 import GlaExts ( Word(..), Int(..), shiftRL# )
187 #else
188 import Data.Word
189 #endif
190
191 infixl 9 \\{-This comment teaches CPP correct behaviour -}
192
193 -- A "Nat" is a natural machine word (an unsigned Int)
194 type Nat = Word
195
196 natFromInt :: Key -> Nat
197 natFromInt i = fromIntegral i
198
199 intFromNat :: Nat -> Key
200 intFromNat w = fromIntegral w
201
202 shiftRL :: Nat -> Key -> Nat
203 #if __GLASGOW_HASKELL__
204 {--------------------------------------------------------------------
205   GHC: use unboxing to get @shiftRL@ inlined.
206 --------------------------------------------------------------------}
207 shiftRL (W# x) (I# i)
208   = W# (shiftRL# x i)
209 #else
210 shiftRL x i   = shiftR x i
211 #endif
212
213 {--------------------------------------------------------------------
214   Operators
215 --------------------------------------------------------------------}
216
217 -- | /O(min(n,W))/. Find the value at a key.
218 -- Calls 'error' when the element can not be found.
219
220 (!) :: IntMap a -> Key -> a
221 m ! k    = find' k m
222
223 -- | /O(n+m)/. See 'difference'.
224 (\\) :: IntMap a -> IntMap b -> IntMap a
225 m1 \\ m2 = difference m1 m2
226
227 {--------------------------------------------------------------------
228   Types  
229 --------------------------------------------------------------------}
230 -- | A map of integers to values @a@.
231 data IntMap a = Nil
232               | Tip {-# UNPACK #-} !Key a
233               | Bin {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask !(IntMap a) !(IntMap a) 
234
235 type Prefix = Int
236 type Mask   = Int
237 type Key    = Int
238
239 instance Monoid (IntMap a) where
240     mempty  = empty
241     mappend = union
242     mconcat = unions
243
244 instance Foldable IntMap where
245     foldMap f Nil = mempty
246     foldMap f (Tip _k v) = f v
247     foldMap f (Bin _ _ l r) = foldMap f l `mappend` foldMap f r
248
249 #if __GLASGOW_HASKELL__
250
251 {--------------------------------------------------------------------
252   A Data instance  
253 --------------------------------------------------------------------}
254
255 -- This instance preserves data abstraction at the cost of inefficiency.
256 -- We omit reflection services for the sake of data abstraction.
257
258 instance Data a => Data (IntMap a) where
259   gfoldl f z im = z fromList `f` (toList im)
260   toConstr _    = error "toConstr"
261   gunfold _ _   = error "gunfold"
262   dataTypeOf _  = mkNorepType "Data.IntMap.IntMap"
263   dataCast1 f   = gcast1 f
264
265 #endif
266
267 {--------------------------------------------------------------------
268   Query
269 --------------------------------------------------------------------}
270 -- | /O(1)/. Is the map empty?
271 null :: IntMap a -> Bool
272 null Nil   = True
273 null other = False
274
275 -- | /O(n)/. Number of elements in the map.
276 size :: IntMap a -> Int
277 size t
278   = case t of
279       Bin p m l r -> size l + size r
280       Tip k x -> 1
281       Nil     -> 0
282
283 -- | /O(min(n,W))/. Is the key a member of the map?
284 member :: Key -> IntMap a -> Bool
285 member k m
286   = case lookup k m of
287       Nothing -> False
288       Just x  -> True
289     
290 -- | /O(log n)/. Is the key not a member of the map?
291 notMember :: Key -> IntMap a -> Bool
292 notMember k m = not $ member k m
293
294 -- | /O(min(n,W))/. Lookup the value at a key in the map.
295 lookup :: (Monad m) => Key -> IntMap a -> m a
296 lookup k t = case lookup' k t of
297     Just x -> return x
298     Nothing -> fail "Data.IntMap.lookup: Key not found"
299
300 lookup' :: Key -> IntMap a -> Maybe a
301 lookup' k t
302   = let nk = natFromInt k  in seq nk (lookupN nk t)
303
304 lookupN :: Nat -> IntMap a -> Maybe a
305 lookupN k t
306   = case t of
307       Bin p m l r 
308         | zeroN k (natFromInt m) -> lookupN k l
309         | otherwise              -> lookupN k r
310       Tip kx x 
311         | (k == natFromInt kx)  -> Just x
312         | otherwise             -> Nothing
313       Nil -> Nothing
314
315 find' :: Key -> IntMap a -> a
316 find' k m
317   = case lookup k m of
318       Nothing -> error ("IntMap.find: key " ++ show k ++ " is not an element of the map")
319       Just x  -> x
320
321
322 -- | /O(min(n,W))/. The expression @('findWithDefault' def k map)@
323 -- returns the value at key @k@ or returns @def@ when the key is not an
324 -- element of the map.
325 findWithDefault :: a -> Key -> IntMap a -> a
326 findWithDefault def k m
327   = case lookup k m of
328       Nothing -> def
329       Just x  -> x
330
331 {--------------------------------------------------------------------
332   Construction
333 --------------------------------------------------------------------}
334 -- | /O(1)/. The empty map.
335 empty :: IntMap a
336 empty
337   = Nil
338
339 -- | /O(1)/. A map of one element.
340 singleton :: Key -> a -> IntMap a
341 singleton k x
342   = Tip k x
343
344 {--------------------------------------------------------------------
345   Insert
346 --------------------------------------------------------------------}
347 -- | /O(min(n,W))/. Insert a new key\/value pair in the map.
348 -- If the key is already present in the map, the associated value is
349 -- replaced with the supplied value, i.e. 'insert' is equivalent to
350 -- @'insertWith' 'const'@.
351 insert :: Key -> a -> IntMap a -> IntMap a
352 insert k x t
353   = case t of
354       Bin p m l r 
355         | nomatch k p m -> join k (Tip k x) p t
356         | zero k m      -> Bin p m (insert k x l) r
357         | otherwise     -> Bin p m l (insert k x r)
358       Tip ky y 
359         | k==ky         -> Tip k x
360         | otherwise     -> join k (Tip k x) ky t
361       Nil -> Tip k x
362
363 -- right-biased insertion, used by 'union'
364 -- | /O(min(n,W))/. Insert with a combining function.
365 -- @'insertWith' f key value mp@ 
366 -- will insert the pair (key, value) into @mp@ if key does
367 -- not exist in the map. If the key does exist, the function will
368 -- insert @f new_value old_value@.
369 insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
370 insertWith f k x t
371   = insertWithKey (\k x y -> f x y) k x t
372
373 -- | /O(min(n,W))/. Insert with a combining function.
374 -- @'insertWithKey' f key value mp@ 
375 -- will insert the pair (key, value) into @mp@ if key does
376 -- not exist in the map. If the key does exist, the function will
377 -- insert @f key new_value old_value@.
378 insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
379 insertWithKey f k x t
380   = case t of
381       Bin p m l r 
382         | nomatch k p m -> join k (Tip k x) p t
383         | zero k m      -> Bin p m (insertWithKey f k x l) r
384         | otherwise     -> Bin p m l (insertWithKey f k x r)
385       Tip ky y 
386         | k==ky         -> Tip k (f k x y)
387         | otherwise     -> join k (Tip k x) ky t
388       Nil -> Tip k x
389
390
391 -- | /O(min(n,W))/. The expression (@'insertLookupWithKey' f k x map@)
392 -- is a pair where the first element is equal to (@'lookup' k map@)
393 -- and the second element equal to (@'insertWithKey' f k x map@).
394 insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)
395 insertLookupWithKey f k x t
396   = case t of
397       Bin p m l r 
398         | nomatch k p m -> (Nothing,join k (Tip k x) p t)
399         | zero k m      -> let (found,l') = insertLookupWithKey f k x l in (found,Bin p m l' r)
400         | otherwise     -> let (found,r') = insertLookupWithKey f k x r in (found,Bin p m l r')
401       Tip ky y 
402         | k==ky         -> (Just y,Tip k (f k x y))
403         | otherwise     -> (Nothing,join k (Tip k x) ky t)
404       Nil -> (Nothing,Tip k x)
405
406
407 {--------------------------------------------------------------------
408   Deletion
409   [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
410 --------------------------------------------------------------------}
411 -- | /O(min(n,W))/. Delete a key and its value from the map. When the key is not
412 -- a member of the map, the original map is returned.
413 delete :: Key -> IntMap a -> IntMap a
414 delete k t
415   = case t of
416       Bin p m l r 
417         | nomatch k p m -> t
418         | zero k m      -> bin p m (delete k l) r
419         | otherwise     -> bin p m l (delete k r)
420       Tip ky y 
421         | k==ky         -> Nil
422         | otherwise     -> t
423       Nil -> Nil
424
425 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
426 -- a member of the map, the original map is returned.
427 adjust ::  (a -> a) -> Key -> IntMap a -> IntMap a
428 adjust f k m
429   = adjustWithKey (\k x -> f x) k m
430
431 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
432 -- a member of the map, the original map is returned.
433 adjustWithKey ::  (Key -> a -> a) -> Key -> IntMap a -> IntMap a
434 adjustWithKey f k m
435   = updateWithKey (\k x -> Just (f k x)) k m
436
437 -- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
438 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
439 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
440 update ::  (a -> Maybe a) -> Key -> IntMap a -> IntMap a
441 update f k m
442   = updateWithKey (\k x -> f x) k m
443
444 -- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
445 -- at @k@ (if it is in the map). If (@f k x@) is 'Nothing', the element is
446 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
447 updateWithKey ::  (Key -> a -> Maybe a) -> Key -> IntMap a -> IntMap a
448 updateWithKey f k t
449   = case t of
450       Bin p m l r 
451         | nomatch k p m -> t
452         | zero k m      -> bin p m (updateWithKey f k l) r
453         | otherwise     -> bin p m l (updateWithKey f k r)
454       Tip ky y 
455         | k==ky         -> case (f k y) of
456                              Just y' -> Tip ky y'
457                              Nothing -> Nil
458         | otherwise     -> t
459       Nil -> Nil
460
461 -- | /O(min(n,W))/. Lookup and update.
462 updateLookupWithKey ::  (Key -> a -> Maybe a) -> Key -> IntMap a -> (Maybe a,IntMap a)
463 updateLookupWithKey f k t
464   = case t of
465       Bin p m l r 
466         | nomatch k p m -> (Nothing,t)
467         | zero k m      -> let (found,l') = updateLookupWithKey f k l in (found,bin p m l' r)
468         | otherwise     -> let (found,r') = updateLookupWithKey f k r in (found,bin p m l r')
469       Tip ky y 
470         | k==ky         -> case (f k y) of
471                              Just y' -> (Just y,Tip ky y')
472                              Nothing -> (Just y,Nil)
473         | otherwise     -> (Nothing,t)
474       Nil -> (Nothing,Nil)
475
476
477
478 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
479 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
480 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@
481 alter f k t
482   = case t of
483       Bin p m l r 
484         | nomatch k p m -> case f Nothing of 
485                              Nothing -> t
486                              Just x -> join k (Tip k x) p t
487         | zero k m      -> bin p m (alter f k l) r
488         | otherwise     -> bin p m l (alter f k r)
489       Tip ky y          
490         | k==ky         -> case f (Just y) of
491                              Just x -> Tip ky x
492                              Nothing -> Nil
493         | otherwise     -> case f Nothing of
494                              Just x -> join k (Tip k x) ky t
495                              Nothing -> Tip ky y
496       Nil               -> case f Nothing of
497                              Just x -> Tip k x
498                              Nothing -> Nil
499
500
501 {--------------------------------------------------------------------
502   Union
503 --------------------------------------------------------------------}
504 -- | The union of a list of maps.
505 unions :: [IntMap a] -> IntMap a
506 unions xs
507   = foldlStrict union empty xs
508
509 -- | The union of a list of maps, with a combining operation
510 unionsWith :: (a->a->a) -> [IntMap a] -> IntMap a
511 unionsWith f ts
512   = foldlStrict (unionWith f) empty ts
513
514 -- | /O(n+m)/. The (left-biased) union of two maps. 
515 -- It prefers the first map when duplicate keys are encountered,
516 -- i.e. (@'union' == 'unionWith' 'const'@).
517 union :: IntMap a -> IntMap a -> IntMap a
518 union t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
519   | shorter m1 m2  = union1
520   | shorter m2 m1  = union2
521   | p1 == p2       = Bin p1 m1 (union l1 l2) (union r1 r2)
522   | otherwise      = join p1 t1 p2 t2
523   where
524     union1  | nomatch p2 p1 m1  = join p1 t1 p2 t2
525             | zero p2 m1        = Bin p1 m1 (union l1 t2) r1
526             | otherwise         = Bin p1 m1 l1 (union r1 t2)
527
528     union2  | nomatch p1 p2 m2  = join p1 t1 p2 t2
529             | zero p1 m2        = Bin p2 m2 (union t1 l2) r2
530             | otherwise         = Bin p2 m2 l2 (union t1 r2)
531
532 union (Tip k x) t = insert k x t
533 union t (Tip k x) = insertWith (\x y -> y) k x t  -- right bias
534 union Nil t       = t
535 union t Nil       = t
536
537 -- | /O(n+m)/. The union with a combining function. 
538 unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
539 unionWith f m1 m2
540   = unionWithKey (\k x y -> f x y) m1 m2
541
542 -- | /O(n+m)/. The union with a combining function. 
543 unionWithKey :: (Key -> a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
544 unionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
545   | shorter m1 m2  = union1
546   | shorter m2 m1  = union2
547   | p1 == p2       = Bin p1 m1 (unionWithKey f l1 l2) (unionWithKey f r1 r2)
548   | otherwise      = join p1 t1 p2 t2
549   where
550     union1  | nomatch p2 p1 m1  = join p1 t1 p2 t2
551             | zero p2 m1        = Bin p1 m1 (unionWithKey f l1 t2) r1
552             | otherwise         = Bin p1 m1 l1 (unionWithKey f r1 t2)
553
554     union2  | nomatch p1 p2 m2  = join p1 t1 p2 t2
555             | zero p1 m2        = Bin p2 m2 (unionWithKey f t1 l2) r2
556             | otherwise         = Bin p2 m2 l2 (unionWithKey f t1 r2)
557
558 unionWithKey f (Tip k x) t = insertWithKey f k x t
559 unionWithKey f t (Tip k x) = insertWithKey (\k x y -> f k y x) k x t  -- right bias
560 unionWithKey f Nil t  = t
561 unionWithKey f t Nil  = t
562
563 {--------------------------------------------------------------------
564   Difference
565 --------------------------------------------------------------------}
566 -- | /O(n+m)/. Difference between two maps (based on keys). 
567 difference :: IntMap a -> IntMap b -> IntMap a
568 difference t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
569   | shorter m1 m2  = difference1
570   | shorter m2 m1  = difference2
571   | p1 == p2       = bin p1 m1 (difference l1 l2) (difference r1 r2)
572   | otherwise      = t1
573   where
574     difference1 | nomatch p2 p1 m1  = t1
575                 | zero p2 m1        = bin p1 m1 (difference l1 t2) r1
576                 | otherwise         = bin p1 m1 l1 (difference r1 t2)
577
578     difference2 | nomatch p1 p2 m2  = t1
579                 | zero p1 m2        = difference t1 l2
580                 | otherwise         = difference t1 r2
581
582 difference t1@(Tip k x) t2 
583   | member k t2  = Nil
584   | otherwise    = t1
585
586 difference Nil t       = Nil
587 difference t (Tip k x) = delete k t
588 difference t Nil       = t
589
590 -- | /O(n+m)/. Difference with a combining function. 
591 differenceWith :: (a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
592 differenceWith f m1 m2
593   = differenceWithKey (\k x y -> f x y) m1 m2
594
595 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
596 -- encountered, the combining function is applied to the key and both values.
597 -- If it returns 'Nothing', the element is discarded (proper set difference).
598 -- If it returns (@'Just' y@), the element is updated with a new value @y@. 
599 differenceWithKey :: (Key -> a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
600 differenceWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
601   | shorter m1 m2  = difference1
602   | shorter m2 m1  = difference2
603   | p1 == p2       = bin p1 m1 (differenceWithKey f l1 l2) (differenceWithKey f r1 r2)
604   | otherwise      = t1
605   where
606     difference1 | nomatch p2 p1 m1  = t1
607                 | zero p2 m1        = bin p1 m1 (differenceWithKey f l1 t2) r1
608                 | otherwise         = bin p1 m1 l1 (differenceWithKey f r1 t2)
609
610     difference2 | nomatch p1 p2 m2  = t1
611                 | zero p1 m2        = differenceWithKey f t1 l2
612                 | otherwise         = differenceWithKey f t1 r2
613
614 differenceWithKey f t1@(Tip k x) t2 
615   = case lookup k t2 of
616       Just y  -> case f k x y of
617                    Just y' -> Tip k y'
618                    Nothing -> Nil
619       Nothing -> t1
620
621 differenceWithKey f Nil t       = Nil
622 differenceWithKey f t (Tip k y) = updateWithKey (\k x -> f k x y) k t
623 differenceWithKey f t Nil       = t
624
625
626 {--------------------------------------------------------------------
627   Intersection
628 --------------------------------------------------------------------}
629 -- | /O(n+m)/. The (left-biased) intersection of two maps (based on keys). 
630 intersection :: IntMap a -> IntMap b -> IntMap a
631 intersection t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
632   | shorter m1 m2  = intersection1
633   | shorter m2 m1  = intersection2
634   | p1 == p2       = bin p1 m1 (intersection l1 l2) (intersection r1 r2)
635   | otherwise      = Nil
636   where
637     intersection1 | nomatch p2 p1 m1  = Nil
638                   | zero p2 m1        = intersection l1 t2
639                   | otherwise         = intersection r1 t2
640
641     intersection2 | nomatch p1 p2 m2  = Nil
642                   | zero p1 m2        = intersection t1 l2
643                   | otherwise         = intersection t1 r2
644
645 intersection t1@(Tip k x) t2 
646   | member k t2  = t1
647   | otherwise    = Nil
648 intersection t (Tip k x) 
649   = case lookup k t of
650       Just y  -> Tip k y
651       Nothing -> Nil
652 intersection Nil t = Nil
653 intersection t Nil = Nil
654
655 -- | /O(n+m)/. The intersection with a combining function. 
656 intersectionWith :: (a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
657 intersectionWith f m1 m2
658   = intersectionWithKey (\k x y -> f x y) m1 m2
659
660 -- | /O(n+m)/. The intersection with a combining function. 
661 intersectionWithKey :: (Key -> a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
662 intersectionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
663   | shorter m1 m2  = intersection1
664   | shorter m2 m1  = intersection2
665   | p1 == p2       = bin p1 m1 (intersectionWithKey f l1 l2) (intersectionWithKey f r1 r2)
666   | otherwise      = Nil
667   where
668     intersection1 | nomatch p2 p1 m1  = Nil
669                   | zero p2 m1        = intersectionWithKey f l1 t2
670                   | otherwise         = intersectionWithKey f r1 t2
671
672     intersection2 | nomatch p1 p2 m2  = Nil
673                   | zero p1 m2        = intersectionWithKey f t1 l2
674                   | otherwise         = intersectionWithKey f t1 r2
675
676 intersectionWithKey f t1@(Tip k x) t2 
677   = case lookup k t2 of
678       Just y  -> Tip k (f k x y)
679       Nothing -> Nil
680 intersectionWithKey f t1 (Tip k y) 
681   = case lookup k t1 of
682       Just x  -> Tip k (f k x y)
683       Nothing -> Nil
684 intersectionWithKey f Nil t = Nil
685 intersectionWithKey f t Nil = Nil
686
687
688 {--------------------------------------------------------------------
689   Min\/Max
690 --------------------------------------------------------------------}
691
692 -- | /O(log n)/. Update the value at the minimal key.
693 updateMinWithKey :: (Key -> a -> a) -> IntMap a -> IntMap a
694 updateMinWithKey f t
695     = case t of
696         Bin p m l r | m < 0 -> let t' = updateMinWithKeyUnsigned f l in Bin p m t' r
697         Bin p m l r         -> let t' = updateMinWithKeyUnsigned f r in Bin p m l t'
698         Tip k y -> Tip k (f k y)
699         Nil -> error "maxView: empty map has no maximal element"
700
701 updateMinWithKeyUnsigned f t
702     = case t of
703         Bin p m l r -> let t' = updateMinWithKeyUnsigned f r in Bin p m l t'
704         Tip k y -> Tip k (f k y)
705
706 -- | /O(log n)/. Update the value at the maximal key.
707 updateMaxWithKey :: (Key -> a -> a) -> IntMap a -> IntMap a
708 updateMaxWithKey f t
709     = case t of
710         Bin p m l r | m < 0 -> let t' = updateMaxWithKeyUnsigned f r in Bin p m r t'
711         Bin p m l r         -> let t' = updateMaxWithKeyUnsigned f l in Bin p m t' l
712         Tip k y -> Tip k (f k y)
713         Nil -> error "maxView: empty map has no maximal element"
714
715 updateMaxWithKeyUnsigned f t
716     = case t of
717         Bin p m l r -> let t' = updateMaxWithKeyUnsigned f r in Bin p m l t'
718         Tip k y -> Tip k (f k y)
719
720
721 -- | /O(log n)/. Retrieves the maximal (key,value) couple of the map, and the map stripped from that element.
722 -- @fail@s (in the monad) when passed an empty map.
723 maxViewWithKey :: (Monad m) => IntMap a -> m ((Key, a), IntMap a)
724 maxViewWithKey t
725     = case t of
726         Bin p m l r | m < 0 -> let (result, t') = maxViewUnsigned l in return (result, bin p m t' r)
727         Bin p m l r         -> let (result, t') = maxViewUnsigned r in return (result, bin p m l t')
728         Tip k y -> return ((k,y), Nil)
729         Nil -> fail "maxView: empty map has no maximal element"
730
731 maxViewUnsigned t 
732     = case t of
733         Bin p m l r -> let (result,t') = maxViewUnsigned r in (result,bin p m l t')
734         Tip k y -> ((k,y), Nil)
735
736 -- | /O(log n)/. Retrieves the minimal (key,value) couple of the map, and the map stripped from that element.
737 -- @fail@s (in the monad) when passed an empty map.
738 minViewWithKey :: (Monad m) => IntMap a -> m ((Key, a), IntMap a)
739 minViewWithKey t
740     = case t of
741         Bin p m l r | m < 0 -> let (result, t') = minViewUnsigned r in return (result, bin p m l t')
742         Bin p m l r         -> let (result, t') = minViewUnsigned l in return (result, bin p m t' r)
743         Tip k y -> return ((k,y),Nil)
744         Nil -> fail "minView: empty map has no minimal element"
745
746 minViewUnsigned t 
747     = case t of
748         Bin p m l r -> let (result,t') = minViewUnsigned l in (result,bin p m t' r)
749         Tip k y -> ((k,y),Nil)
750
751
752 -- | /O(log n)/. Update the value at the maximal key.
753 updateMax :: (a -> a) -> IntMap a -> IntMap a
754 updateMax f = updateMaxWithKey (const f)
755
756 -- | /O(log n)/. Update the value at the minimal key.
757 updateMin :: (a -> a) -> IntMap a -> IntMap a
758 updateMin f = updateMinWithKey (const f)
759
760
761 -- Duplicate the Identity monad here because base < mtl.
762 newtype Identity a = Identity { runIdentity :: a }
763 instance Monad Identity where
764         return a = Identity a
765         m >>= k  = k (runIdentity m)
766 -- Similar to the Arrow instance.
767 first f (x,y) = (f x,y)
768
769
770 -- | /O(log n)/. Retrieves the maximal key of the map, and the map stripped from that element.
771 -- @fail@s (in the monad) when passed an empty map.
772 maxView t = liftM (first snd) (maxViewWithKey t)
773
774 -- | /O(log n)/. Retrieves the minimal key of the map, and the map stripped from that element.
775 -- @fail@s (in the monad) when passed an empty map.
776 minView t = liftM (first snd) (minViewWithKey t)
777
778 -- | /O(log n)/. Delete and find the maximal element.
779 deleteFindMax = runIdentity . maxView
780
781 -- | /O(log n)/. Delete and find the minimal element.
782 deleteFindMin = runIdentity . minView
783
784 -- | /O(log n)/. The minimal key of the map.
785 findMin = fst . runIdentity . minView
786
787 -- | /O(log n)/. The maximal key of the map.
788 findMax = fst . runIdentity . maxView
789
790 -- | /O(log n)/. Delete the minimal key.
791 deleteMin = snd . runIdentity . minView
792
793 -- | /O(log n)/. Delete the maximal key.
794 deleteMax = snd . runIdentity . maxView
795
796
797 {--------------------------------------------------------------------
798   Submap
799 --------------------------------------------------------------------}
800 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal). 
801 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
802 isProperSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
803 isProperSubmapOf m1 m2
804   = isProperSubmapOfBy (==) m1 m2
805
806 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
807  The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
808  @m1@ and @m2@ are not equal,
809  all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
810  applied to their respective values. For example, the following 
811  expressions are all 'True':
812  
813   > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
814   > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
815
816  But the following are all 'False':
817  
818   > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
819   > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
820   > isProperSubmapOfBy (<)  (fromList [(1,1)])       (fromList [(1,1),(2,2)])
821 -}
822 isProperSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
823 isProperSubmapOfBy pred t1 t2
824   = case submapCmp pred t1 t2 of 
825       LT -> True
826       ge -> False
827
828 submapCmp pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
829   | shorter m1 m2  = GT
830   | shorter m2 m1  = submapCmpLt
831   | p1 == p2       = submapCmpEq
832   | otherwise      = GT  -- disjoint
833   where
834     submapCmpLt | nomatch p1 p2 m2  = GT
835                 | zero p1 m2        = submapCmp pred t1 l2
836                 | otherwise         = submapCmp pred t1 r2
837     submapCmpEq = case (submapCmp pred l1 l2, submapCmp pred r1 r2) of
838                     (GT,_ ) -> GT
839                     (_ ,GT) -> GT
840                     (EQ,EQ) -> EQ
841                     other   -> LT
842
843 submapCmp pred (Bin p m l r) t  = GT
844 submapCmp pred (Tip kx x) (Tip ky y)  
845   | (kx == ky) && pred x y = EQ
846   | otherwise              = GT  -- disjoint
847 submapCmp pred (Tip k x) t      
848   = case lookup k t of
849      Just y  | pred x y -> LT
850      other   -> GT -- disjoint
851 submapCmp pred Nil Nil = EQ
852 submapCmp pred Nil t   = LT
853
854 -- | /O(n+m)/. Is this a submap?
855 -- Defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
856 isSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
857 isSubmapOf m1 m2
858   = isSubmapOfBy (==) m1 m2
859
860 {- | /O(n+m)/. 
861  The expression (@'isSubmapOfBy' f m1 m2@) returns 'True' if
862  all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
863  applied to their respective values. For example, the following 
864  expressions are all 'True':
865  
866   > isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
867   > isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
868   > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
869
870  But the following are all 'False':
871  
872   > isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)])
873   > isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
874   > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
875 -}
876
877 isSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
878 isSubmapOfBy pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
879   | shorter m1 m2  = False
880   | shorter m2 m1  = match p1 p2 m2 && (if zero p1 m2 then isSubmapOfBy pred t1 l2
881                                                       else isSubmapOfBy pred t1 r2)                     
882   | otherwise      = (p1==p2) && isSubmapOfBy pred l1 l2 && isSubmapOfBy pred r1 r2
883 isSubmapOfBy pred (Bin p m l r) t  = False
884 isSubmapOfBy pred (Tip k x) t      = case lookup k t of
885                                    Just y  -> pred x y
886                                    Nothing -> False 
887 isSubmapOfBy pred Nil t            = True
888
889 {--------------------------------------------------------------------
890   Mapping
891 --------------------------------------------------------------------}
892 -- | /O(n)/. Map a function over all values in the map.
893 map :: (a -> b) -> IntMap a -> IntMap b
894 map f m
895   = mapWithKey (\k x -> f x) m
896
897 -- | /O(n)/. Map a function over all values in the map.
898 mapWithKey :: (Key -> a -> b) -> IntMap a -> IntMap b
899 mapWithKey f t  
900   = case t of
901       Bin p m l r -> Bin p m (mapWithKey f l) (mapWithKey f r)
902       Tip k x     -> Tip k (f k x)
903       Nil         -> Nil
904
905 -- | /O(n)/. The function @'mapAccum'@ threads an accumulating
906 -- argument through the map in ascending order of keys.
907 mapAccum :: (a -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
908 mapAccum f a m
909   = mapAccumWithKey (\a k x -> f a x) a m
910
911 -- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating
912 -- argument through the map in ascending order of keys.
913 mapAccumWithKey :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
914 mapAccumWithKey f a t
915   = mapAccumL f a t
916
917 -- | /O(n)/. The function @'mapAccumL'@ threads an accumulating
918 -- argument through the map in ascending order of keys.
919 mapAccumL :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
920 mapAccumL f a t
921   = case t of
922       Bin p m l r -> let (a1,l') = mapAccumL f a l
923                          (a2,r') = mapAccumL f a1 r
924                      in (a2,Bin p m l' r')
925       Tip k x     -> let (a',x') = f a k x in (a',Tip k x')
926       Nil         -> (a,Nil)
927
928
929 -- | /O(n)/. The function @'mapAccumR'@ threads an accumulating
930 -- argument throught the map in descending order of keys.
931 mapAccumR :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
932 mapAccumR f a t
933   = case t of
934       Bin p m l r -> let (a1,r') = mapAccumR f a r
935                          (a2,l') = mapAccumR f a1 l
936                      in (a2,Bin p m l' r')
937       Tip k x     -> let (a',x') = f a k x in (a',Tip k x')
938       Nil         -> (a,Nil)
939
940 {--------------------------------------------------------------------
941   Filter
942 --------------------------------------------------------------------}
943 -- | /O(n)/. Filter all values that satisfy some predicate.
944 filter :: (a -> Bool) -> IntMap a -> IntMap a
945 filter p m
946   = filterWithKey (\k x -> p x) m
947
948 -- | /O(n)/. Filter all keys\/values that satisfy some predicate.
949 filterWithKey :: (Key -> a -> Bool) -> IntMap a -> IntMap a
950 filterWithKey pred t
951   = case t of
952       Bin p m l r 
953         -> bin p m (filterWithKey pred l) (filterWithKey pred r)
954       Tip k x 
955         | pred k x  -> t
956         | otherwise -> Nil
957       Nil -> Nil
958
959 -- | /O(n)/. partition the map according to some predicate. The first
960 -- map contains all elements that satisfy the predicate, the second all
961 -- elements that fail the predicate. See also 'split'.
962 partition :: (a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
963 partition p m
964   = partitionWithKey (\k x -> p x) m
965
966 -- | /O(n)/. partition the map according to some predicate. The first
967 -- map contains all elements that satisfy the predicate, the second all
968 -- elements that fail the predicate. See also 'split'.
969 partitionWithKey :: (Key -> a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
970 partitionWithKey pred t
971   = case t of
972       Bin p m l r 
973         -> let (l1,l2) = partitionWithKey pred l
974                (r1,r2) = partitionWithKey pred r
975            in (bin p m l1 r1, bin p m l2 r2)
976       Tip k x 
977         | pred k x  -> (t,Nil)
978         | otherwise -> (Nil,t)
979       Nil -> (Nil,Nil)
980
981 -- | /O(n)/. Map values and collect the 'Just' results.
982 mapMaybe :: (a -> Maybe b) -> IntMap a -> IntMap b
983 mapMaybe f m
984   = mapMaybeWithKey (\k x -> f x) m
985
986 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
987 mapMaybeWithKey :: (Key -> a -> Maybe b) -> IntMap a -> IntMap b
988 mapMaybeWithKey f (Bin p m l r)
989   = bin p m (mapMaybeWithKey f l) (mapMaybeWithKey f r)
990 mapMaybeWithKey f (Tip k x) = case f k x of
991   Just y  -> Tip k y
992   Nothing -> Nil
993 mapMaybeWithKey f Nil = Nil
994
995 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
996 mapEither :: (a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)
997 mapEither f m
998   = mapEitherWithKey (\k x -> f x) m
999
1000 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
1001 mapEitherWithKey :: (Key -> a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)
1002 mapEitherWithKey f (Bin p m l r)
1003   = (bin p m l1 r1, bin p m l2 r2)
1004   where
1005     (l1,l2) = mapEitherWithKey f l
1006     (r1,r2) = mapEitherWithKey f r
1007 mapEitherWithKey f (Tip k x) = case f k x of
1008   Left y  -> (Tip k y, Nil)
1009   Right z -> (Nil, Tip k z)
1010 mapEitherWithKey f Nil = (Nil, Nil)
1011
1012 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@
1013 -- where all keys in @map1@ are lower than @k@ and all keys in
1014 -- @map2@ larger than @k@. Any key equal to @k@ is found in neither @map1@ nor @map2@.
1015 split :: Key -> IntMap a -> (IntMap a,IntMap a)
1016 split k t
1017   = case t of
1018       Bin p m l r 
1019           | m < 0 -> (if k >= 0 -- handle negative numbers.
1020                       then let (lt,gt) = split' k l in (union r lt, gt)
1021                       else let (lt,gt) = split' k r in (lt, union gt l))
1022           | otherwise   -> split' k t
1023       Tip ky y 
1024         | k>ky      -> (t,Nil)
1025         | k<ky      -> (Nil,t)
1026         | otherwise -> (Nil,Nil)
1027       Nil -> (Nil,Nil)
1028
1029 split' :: Key -> IntMap a -> (IntMap a,IntMap a)
1030 split' k t
1031   = case t of
1032       Bin p m l r
1033         | nomatch k p m -> if k>p then (t,Nil) else (Nil,t)
1034         | zero k m  -> let (lt,gt) = split k l in (lt,union gt r)
1035         | otherwise -> let (lt,gt) = split k r in (union l lt,gt)
1036       Tip ky y 
1037         | k>ky      -> (t,Nil)
1038         | k<ky      -> (Nil,t)
1039         | otherwise -> (Nil,Nil)
1040       Nil -> (Nil,Nil)
1041
1042 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1043 -- key was found in the original map.
1044 splitLookup :: Key -> IntMap a -> (IntMap a,Maybe a,IntMap a)
1045 splitLookup k t
1046   = case t of
1047       Bin p m l r
1048           | m < 0 -> (if k >= 0 -- handle negative numbers.
1049                       then let (lt,found,gt) = splitLookup' k l in (union r lt,found, gt)
1050                       else let (lt,found,gt) = splitLookup' k r in (lt,found, union gt l))
1051           | otherwise   -> splitLookup' k t
1052       Tip ky y 
1053         | k>ky      -> (t,Nothing,Nil)
1054         | k<ky      -> (Nil,Nothing,t)
1055         | otherwise -> (Nil,Just y,Nil)
1056       Nil -> (Nil,Nothing,Nil)
1057
1058 splitLookup' :: Key -> IntMap a -> (IntMap a,Maybe a,IntMap a)
1059 splitLookup' k t
1060   = case t of
1061       Bin p m l r
1062         | nomatch k p m -> if k>p then (t,Nothing,Nil) else (Nil,Nothing,t)
1063         | zero k m  -> let (lt,found,gt) = splitLookup k l in (lt,found,union gt r)
1064         | otherwise -> let (lt,found,gt) = splitLookup k r in (union l lt,found,gt)
1065       Tip ky y 
1066         | k>ky      -> (t,Nothing,Nil)
1067         | k<ky      -> (Nil,Nothing,t)
1068         | otherwise -> (Nil,Just y,Nil)
1069       Nil -> (Nil,Nothing,Nil)
1070
1071 {--------------------------------------------------------------------
1072   Fold
1073 --------------------------------------------------------------------}
1074 -- | /O(n)/. Fold the values in the map, such that
1075 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
1076 -- For example,
1077 --
1078 -- > elems map = fold (:) [] map
1079 --
1080 fold :: (a -> b -> b) -> b -> IntMap a -> b
1081 fold f z t
1082   = foldWithKey (\k x y -> f x y) z t
1083
1084 -- | /O(n)/. Fold the keys and values in the map, such that
1085 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
1086 -- For example,
1087 --
1088 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
1089 --
1090 foldWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b
1091 foldWithKey f z t
1092   = foldr f z t
1093
1094 foldr :: (Key -> a -> b -> b) -> b -> IntMap a -> b
1095 foldr f z t
1096   = case t of
1097       Bin 0 m l r | m < 0 -> foldr' f (foldr' f z l) r  -- put negative numbers before.
1098       Bin _ _ _ _ -> foldr' f z t
1099       Tip k x     -> f k x z
1100       Nil         -> z
1101
1102 foldr' :: (Key -> a -> b -> b) -> b -> IntMap a -> b
1103 foldr' f z t
1104   = case t of
1105       Bin p m l r -> foldr' f (foldr' f z r) l
1106       Tip k x     -> f k x z
1107       Nil         -> z
1108
1109
1110
1111 {--------------------------------------------------------------------
1112   List variations 
1113 --------------------------------------------------------------------}
1114 -- | /O(n)/.
1115 -- Return all elements of the map in the ascending order of their keys.
1116 elems :: IntMap a -> [a]
1117 elems m
1118   = foldWithKey (\k x xs -> x:xs) [] m  
1119
1120 -- | /O(n)/. Return all keys of the map in ascending order.
1121 keys  :: IntMap a -> [Key]
1122 keys m
1123   = foldWithKey (\k x ks -> k:ks) [] m
1124
1125 -- | /O(n*min(n,W))/. The set of all keys of the map.
1126 keysSet :: IntMap a -> IntSet.IntSet
1127 keysSet m = IntSet.fromDistinctAscList (keys m)
1128
1129
1130 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
1131 assocs :: IntMap a -> [(Key,a)]
1132 assocs m
1133   = toList m
1134
1135
1136 {--------------------------------------------------------------------
1137   Lists 
1138 --------------------------------------------------------------------}
1139 -- | /O(n)/. Convert the map to a list of key\/value pairs.
1140 toList :: IntMap a -> [(Key,a)]
1141 toList t
1142   = foldWithKey (\k x xs -> (k,x):xs) [] t
1143
1144 -- | /O(n)/. Convert the map to a list of key\/value pairs where the
1145 -- keys are in ascending order.
1146 toAscList :: IntMap a -> [(Key,a)]
1147 toAscList t   
1148   = -- NOTE: the following algorithm only works for big-endian trees
1149     let (pos,neg) = span (\(k,x) -> k >=0) (foldr (\k x xs -> (k,x):xs) [] t) in neg ++ pos
1150
1151 -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs.
1152 fromList :: [(Key,a)] -> IntMap a
1153 fromList xs
1154   = foldlStrict ins empty xs
1155   where
1156     ins t (k,x)  = insert k x t
1157
1158 -- | /O(n*min(n,W))/.  Create a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1159 fromListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a 
1160 fromListWith f xs
1161   = fromListWithKey (\k x y -> f x y) xs
1162
1163 -- | /O(n*min(n,W))/.  Build a map from a list of key\/value pairs with a combining function. See also fromAscListWithKey'.
1164 fromListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a 
1165 fromListWithKey f xs 
1166   = foldlStrict ins empty xs
1167   where
1168     ins t (k,x) = insertWithKey f k x t
1169
1170 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
1171 -- the keys are in ascending order.
1172 fromAscList :: [(Key,a)] -> IntMap a
1173 fromAscList xs
1174   = fromList xs
1175
1176 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
1177 -- the keys are in ascending order, with a combining function on equal keys.
1178 fromAscListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
1179 fromAscListWith f xs
1180   = fromListWith f xs
1181
1182 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
1183 -- the keys are in ascending order, with a combining function on equal keys.
1184 fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
1185 fromAscListWithKey f xs
1186   = fromListWithKey f xs
1187
1188 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
1189 -- the keys are in ascending order and all distinct.
1190 fromDistinctAscList :: [(Key,a)] -> IntMap a
1191 fromDistinctAscList xs
1192   = fromList xs
1193
1194
1195 {--------------------------------------------------------------------
1196   Eq 
1197 --------------------------------------------------------------------}
1198 instance Eq a => Eq (IntMap a) where
1199   t1 == t2  = equal t1 t2
1200   t1 /= t2  = nequal t1 t2
1201
1202 equal :: Eq a => IntMap a -> IntMap a -> Bool
1203 equal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
1204   = (m1 == m2) && (p1 == p2) && (equal l1 l2) && (equal r1 r2) 
1205 equal (Tip kx x) (Tip ky y)
1206   = (kx == ky) && (x==y)
1207 equal Nil Nil = True
1208 equal t1 t2   = False
1209
1210 nequal :: Eq a => IntMap a -> IntMap a -> Bool
1211 nequal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
1212   = (m1 /= m2) || (p1 /= p2) || (nequal l1 l2) || (nequal r1 r2) 
1213 nequal (Tip kx x) (Tip ky y)
1214   = (kx /= ky) || (x/=y)
1215 nequal Nil Nil = False
1216 nequal t1 t2   = True
1217
1218 {--------------------------------------------------------------------
1219   Ord 
1220 --------------------------------------------------------------------}
1221
1222 instance Ord a => Ord (IntMap a) where
1223     compare m1 m2 = compare (toList m1) (toList m2)
1224
1225 {--------------------------------------------------------------------
1226   Functor 
1227 --------------------------------------------------------------------}
1228
1229 instance Functor IntMap where
1230     fmap = map
1231
1232 {--------------------------------------------------------------------
1233   Show 
1234 --------------------------------------------------------------------}
1235
1236 instance Show a => Show (IntMap a) where
1237   showsPrec d m   = showParen (d > 10) $
1238     showString "fromList " . shows (toList m)
1239
1240 showMap :: (Show a) => [(Key,a)] -> ShowS
1241 showMap []     
1242   = showString "{}" 
1243 showMap (x:xs) 
1244   = showChar '{' . showElem x . showTail xs
1245   where
1246     showTail []     = showChar '}'
1247     showTail (x:xs) = showChar ',' . showElem x . showTail xs
1248     
1249     showElem (k,x)  = shows k . showString ":=" . shows x
1250
1251 {--------------------------------------------------------------------
1252   Read
1253 --------------------------------------------------------------------}
1254 instance (Read e) => Read (IntMap e) where
1255 #ifdef __GLASGOW_HASKELL__
1256   readPrec = parens $ prec 10 $ do
1257     Ident "fromList" <- lexP
1258     xs <- readPrec
1259     return (fromList xs)
1260
1261   readListPrec = readListPrecDefault
1262 #else
1263   readsPrec p = readParen (p > 10) $ \ r -> do
1264     ("fromList",s) <- lex r
1265     (xs,t) <- reads s
1266     return (fromList xs,t)
1267 #endif
1268
1269 {--------------------------------------------------------------------
1270   Typeable
1271 --------------------------------------------------------------------}
1272
1273 #include "Typeable.h"
1274 INSTANCE_TYPEABLE1(IntMap,intMapTc,"IntMap")
1275
1276 {--------------------------------------------------------------------
1277   Debugging
1278 --------------------------------------------------------------------}
1279 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1280 -- in a compressed, hanging format.
1281 showTree :: Show a => IntMap a -> String
1282 showTree s
1283   = showTreeWith True False s
1284
1285
1286 {- | /O(n)/. The expression (@'showTreeWith' hang wide map@) shows
1287  the tree that implements the map. If @hang@ is
1288  'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1289  @wide@ is 'True', an extra wide version is shown.
1290 -}
1291 showTreeWith :: Show a => Bool -> Bool -> IntMap a -> String
1292 showTreeWith hang wide t
1293   | hang      = (showsTreeHang wide [] t) ""
1294   | otherwise = (showsTree wide [] [] t) ""
1295
1296 showsTree :: Show a => Bool -> [String] -> [String] -> IntMap a -> ShowS
1297 showsTree wide lbars rbars t
1298   = case t of
1299       Bin p m l r
1300           -> showsTree wide (withBar rbars) (withEmpty rbars) r .
1301              showWide wide rbars .
1302              showsBars lbars . showString (showBin p m) . showString "\n" .
1303              showWide wide lbars .
1304              showsTree wide (withEmpty lbars) (withBar lbars) l
1305       Tip k x
1306           -> showsBars lbars . showString " " . shows k . showString ":=" . shows x . showString "\n" 
1307       Nil -> showsBars lbars . showString "|\n"
1308
1309 showsTreeHang :: Show a => Bool -> [String] -> IntMap a -> ShowS
1310 showsTreeHang wide bars t
1311   = case t of
1312       Bin p m l r
1313           -> showsBars bars . showString (showBin p m) . showString "\n" . 
1314              showWide wide bars .
1315              showsTreeHang wide (withBar bars) l .
1316              showWide wide bars .
1317              showsTreeHang wide (withEmpty bars) r
1318       Tip k x
1319           -> showsBars bars . showString " " . shows k . showString ":=" . shows x . showString "\n" 
1320       Nil -> showsBars bars . showString "|\n" 
1321       
1322 showBin p m
1323   = "*" -- ++ show (p,m)
1324
1325 showWide wide bars 
1326   | wide      = showString (concat (reverse bars)) . showString "|\n" 
1327   | otherwise = id
1328
1329 showsBars :: [String] -> ShowS
1330 showsBars bars
1331   = case bars of
1332       [] -> id
1333       _  -> showString (concat (reverse (tail bars))) . showString node
1334
1335 node           = "+--"
1336 withBar bars   = "|  ":bars
1337 withEmpty bars = "   ":bars
1338
1339
1340 {--------------------------------------------------------------------
1341   Helpers
1342 --------------------------------------------------------------------}
1343 {--------------------------------------------------------------------
1344   Join
1345 --------------------------------------------------------------------}
1346 join :: Prefix -> IntMap a -> Prefix -> IntMap a -> IntMap a
1347 join p1 t1 p2 t2
1348   | zero p1 m = Bin p m t1 t2
1349   | otherwise = Bin p m t2 t1
1350   where
1351     m = branchMask p1 p2
1352     p = mask p1 m
1353
1354 {--------------------------------------------------------------------
1355   @bin@ assures that we never have empty trees within a tree.
1356 --------------------------------------------------------------------}
1357 bin :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
1358 bin p m l Nil = l
1359 bin p m Nil r = r
1360 bin p m l r   = Bin p m l r
1361
1362   
1363 {--------------------------------------------------------------------
1364   Endian independent bit twiddling
1365 --------------------------------------------------------------------}
1366 zero :: Key -> Mask -> Bool
1367 zero i m
1368   = (natFromInt i) .&. (natFromInt m) == 0
1369
1370 nomatch,match :: Key -> Prefix -> Mask -> Bool
1371 nomatch i p m
1372   = (mask i m) /= p
1373
1374 match i p m
1375   = (mask i m) == p
1376
1377 mask :: Key -> Mask -> Prefix
1378 mask i m
1379   = maskW (natFromInt i) (natFromInt m)
1380
1381
1382 zeroN :: Nat -> Nat -> Bool
1383 zeroN i m = (i .&. m) == 0
1384
1385 {--------------------------------------------------------------------
1386   Big endian operations  
1387 --------------------------------------------------------------------}
1388 maskW :: Nat -> Nat -> Prefix
1389 maskW i m
1390   = intFromNat (i .&. (complement (m-1) `xor` m))
1391
1392 shorter :: Mask -> Mask -> Bool
1393 shorter m1 m2
1394   = (natFromInt m1) > (natFromInt m2)
1395
1396 branchMask :: Prefix -> Prefix -> Mask
1397 branchMask p1 p2
1398   = intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
1399   
1400 {----------------------------------------------------------------------
1401   Finding the highest bit (mask) in a word [x] can be done efficiently in
1402   three ways:
1403   * convert to a floating point value and the mantissa tells us the 
1404     [log2(x)] that corresponds with the highest bit position. The mantissa 
1405     is retrieved either via the standard C function [frexp] or by some bit 
1406     twiddling on IEEE compatible numbers (float). Note that one needs to 
1407     use at least [double] precision for an accurate mantissa of 32 bit 
1408     numbers.
1409   * use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
1410   * use processor specific assembler instruction (asm).
1411
1412   The most portable way would be [bit], but is it efficient enough?
1413   I have measured the cycle counts of the different methods on an AMD 
1414   Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
1415
1416   highestBitMask: method  cycles
1417                   --------------
1418                    frexp   200
1419                    float    33
1420                    bit      11
1421                    asm      12
1422
1423   highestBit:     method  cycles
1424                   --------------
1425                    frexp   195
1426                    float    33
1427                    bit      11
1428                    asm      11
1429
1430   Wow, the bit twiddling is on today's RISC like machines even faster
1431   than a single CISC instruction (BSR)!
1432 ----------------------------------------------------------------------}
1433
1434 {----------------------------------------------------------------------
1435   [highestBitMask] returns a word where only the highest bit is set.
1436   It is found by first setting all bits in lower positions than the 
1437   highest bit and than taking an exclusive or with the original value.
1438   Allthough the function may look expensive, GHC compiles this into
1439   excellent C code that subsequently compiled into highly efficient
1440   machine code. The algorithm is derived from Jorg Arndt's FXT library.
1441 ----------------------------------------------------------------------}
1442 highestBitMask :: Nat -> Nat
1443 highestBitMask x
1444   = case (x .|. shiftRL x 1) of 
1445      x -> case (x .|. shiftRL x 2) of 
1446       x -> case (x .|. shiftRL x 4) of 
1447        x -> case (x .|. shiftRL x 8) of 
1448         x -> case (x .|. shiftRL x 16) of 
1449          x -> case (x .|. shiftRL x 32) of   -- for 64 bit platforms
1450           x -> (x `xor` (shiftRL x 1))
1451
1452
1453 {--------------------------------------------------------------------
1454   Utilities 
1455 --------------------------------------------------------------------}
1456 foldlStrict f z xs
1457   = case xs of
1458       []     -> z
1459       (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1460
1461 {-
1462 {--------------------------------------------------------------------
1463   Testing
1464 --------------------------------------------------------------------}
1465 testTree :: [Int] -> IntMap Int
1466 testTree xs   = fromList [(x,x*x*30696 `mod` 65521) | x <- xs]
1467 test1 = testTree [1..20]
1468 test2 = testTree [30,29..10]
1469 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1470
1471 {--------------------------------------------------------------------
1472   QuickCheck
1473 --------------------------------------------------------------------}
1474 qcheck prop
1475   = check config prop
1476   where
1477     config = Config
1478       { configMaxTest = 500
1479       , configMaxFail = 5000
1480       , configSize    = \n -> (div n 2 + 3)
1481       , configEvery   = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1482       }
1483
1484
1485 {--------------------------------------------------------------------
1486   Arbitrary, reasonably balanced trees
1487 --------------------------------------------------------------------}
1488 instance Arbitrary a => Arbitrary (IntMap a) where
1489   arbitrary = do{ ks <- arbitrary
1490                 ; xs <- mapM (\k -> do{ x <- arbitrary; return (k,x)}) ks
1491                 ; return (fromList xs)
1492                 }
1493
1494
1495 {--------------------------------------------------------------------
1496   Single, Insert, Delete
1497 --------------------------------------------------------------------}
1498 prop_Single :: Key -> Int -> Bool
1499 prop_Single k x
1500   = (insert k x empty == singleton k x)
1501
1502 prop_InsertDelete :: Key -> Int -> IntMap Int -> Property
1503 prop_InsertDelete k x t
1504   = not (member k t) ==> delete k (insert k x t) == t
1505
1506 prop_UpdateDelete :: Key -> IntMap Int -> Bool  
1507 prop_UpdateDelete k t
1508   = update (const Nothing) k t == delete k t
1509
1510
1511 {--------------------------------------------------------------------
1512   Union
1513 --------------------------------------------------------------------}
1514 prop_UnionInsert :: Key -> Int -> IntMap Int -> Bool
1515 prop_UnionInsert k x t
1516   = union (singleton k x) t == insert k x t
1517
1518 prop_UnionAssoc :: IntMap Int -> IntMap Int -> IntMap Int -> Bool
1519 prop_UnionAssoc t1 t2 t3
1520   = union t1 (union t2 t3) == union (union t1 t2) t3
1521
1522 prop_UnionComm :: IntMap Int -> IntMap Int -> Bool
1523 prop_UnionComm t1 t2
1524   = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1525
1526
1527 prop_Diff :: [(Key,Int)] -> [(Key,Int)] -> Bool
1528 prop_Diff xs ys
1529   =  List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys))) 
1530     == List.sort ((List.\\) (nub (Prelude.map fst xs))  (nub (Prelude.map fst ys)))
1531
1532 prop_Int :: [(Key,Int)] -> [(Key,Int)] -> Bool
1533 prop_Int xs ys
1534   =  List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys))) 
1535     == List.sort (nub ((List.intersect) (Prelude.map fst xs)  (Prelude.map fst ys)))
1536
1537 {--------------------------------------------------------------------
1538   Lists
1539 --------------------------------------------------------------------}
1540 prop_Ordered
1541   = forAll (choose (5,100)) $ \n ->
1542     let xs = [(x,()) | x <- [0..n::Int]] 
1543     in fromAscList xs == fromList xs
1544
1545 prop_List :: [Key] -> Bool
1546 prop_List xs
1547   = (sort (nub xs) == [x | (x,()) <- toAscList (fromList [(x,()) | x <- xs])])
1548 -}