3f3fd04710b9185c7ea8f068d60b0316cb4c78f2
[ghc-base.git] / Data / FiniteMap.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.FiniteMap
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- A finite map implementation, derived from the paper:
12 --         /Efficient sets: a balancing act/, S. Adams,
13 --         Journal of functional programming 3(4) Oct 1993, pp553-562
14 --
15 -----------------------------------------------------------------------------
16
17 -- ToDo: clean up, remove the COMPILING_GHC stuff.
18
19 -- The code is SPECIALIZEd to various highly-desirable types (e.g., Id)
20 -- near the end (only \tr{#ifdef COMPILING_GHC}).
21
22 #ifdef COMPILING_GHC
23 #include "HsVersions.h"
24 #define IF_NOT_GHC(a) {--}
25 #else
26 #define ASSERT(e) {--}
27 #define IF_NOT_GHC(a) a
28 #define COMMA ,
29 #define _tagCmp compare
30 #define _LT LT
31 #define _GT GT
32 #define _EQ EQ
33 #endif
34
35 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)/* NB NB NB */
36 #define OUTPUTABLE_key , Outputable key
37 #else
38 #define OUTPUTABLE_key {--}
39 #endif
40
41 module Data.FiniteMap (
42         -- * The @FiniteMap@ type
43         FiniteMap,              -- abstract type
44
45         -- * Construction
46         emptyFM, unitFM, listToFM,
47
48         -- * Lookup operations
49         lookupFM, lookupWithDefaultFM,
50         elemFM,
51
52         -- * Adding elements
53         addToFM,
54         addToFM_C,
55         addListToFM,
56         addListToFM_C,
57
58         -- * Deleting elements
59         IF_NOT_GHC(delFromFM COMMA)
60         delListFromFM,
61
62         -- * Combination
63         plusFM,
64         plusFM_C,
65
66         -- * Extracting information
67         fmToList, keysFM, eltsFM,
68         sizeFM, isEmptyFM,
69
70         -- * Other operations
71         minusFM,
72         foldFM,
73         IF_NOT_GHC(intersectFM COMMA)
74         IF_NOT_GHC(intersectFM_C COMMA)
75         IF_NOT_GHC(mapFM COMMA filterFM COMMA)
76
77         foldFM_GE, fmToList_GE, keysFM_GE, eltsFM_GE,
78         foldFM_LE, fmToList_LE, keysFM_LE, eltsFM_LE,
79
80         minFM, maxFM,
81
82 #ifdef COMPILING_GHC
83         , bagToFM
84 #endif
85     ) where
86
87 import Prelude -- necessary to get dependencies right
88
89 import Data.Maybe ( isJust )
90 #ifdef __GLASGOW_HASKELL__
91 import GHC.Base
92 #endif
93
94 #ifdef __HADDOCK__
95 import Prelude
96 #endif
97
98 #ifdef COMPILING_GHC
99 IMP_Ubiq(){-uitous-}
100 # ifdef DEBUG
101 import Pretty
102 # endif
103 import Bag      ( foldBag )
104
105 # if ! OMIT_NATIVE_CODEGEN
106 #  define IF_NCG(a) a
107 # else
108 #  define IF_NCG(a) {--}
109 # endif
110 #endif
111
112 -- SIGH: but we use unboxed "sizes"...
113 #if __GLASGOW_HASKELL__
114 #define IF_GHC(a,b) a
115 #else /* not GHC */
116 #define IF_GHC(a,b) b
117 #endif /* not GHC */
118
119
120 -- ---------------------------------------------------------------------------
121 -- The signature of the module
122
123 -- | An empty 'FiniteMap'.
124 emptyFM         :: FiniteMap key elt
125
126 -- | A 'FiniteMap' containing a single mapping
127 unitFM          :: key -> elt -> FiniteMap key elt
128
129 -- | Makes a 'FiniteMap' from a list of @(key,value)@ pairs. In the
130 -- case of duplicates, the last is taken
131 listToFM        :: (Ord key OUTPUTABLE_key) => [(key,elt)] -> FiniteMap key elt
132
133 #ifdef COMPILING_GHC
134 bagToFM         :: (Ord key OUTPUTABLE_key) => Bag (key,elt) -> FiniteMap key elt
135                         -- In the case of duplicates, who knows which is taken
136 #endif
137
138 --      ADDING AND DELETING
139
140 -- | Adds an element to a 'FiniteMap'.  Any previous mapping with the same
141 -- key is overwritten.
142 addToFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
143
144 -- | Adds a list of elements to a 'FiniteMap', in the order given in
145 -- the list.  Overwrites previous mappings.
146 addListToFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
147
148                    -- Combines with previous binding
149                    -- In the combining function, the first argument is the "old" element,
150                    -- while the second is the "new" one.
151
152 -- | Adds an element to a 'FiniteMap'.  If there is already an element
153 -- with the same key, then the specified combination function is used
154 -- to calculate the new value. The already present element is passed as
155 -- the first argument and the new element to add as second.
156 addToFM_C       :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
157                            -> FiniteMap key elt -> key -> elt
158                            -> FiniteMap key elt
159
160 -- | A list version of 'addToFM_C'.  The elements are added in the
161 -- order given in the list.
162 addListToFM_C   :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
163                            -> FiniteMap key elt -> [(key,elt)]
164                            -> FiniteMap key elt
165
166 -- | Deletes an element from a 'FiniteMap'.  If there is no element with
167 -- the specified key, then the original 'FiniteMap' is returned.
168 delFromFM       :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key   -> FiniteMap key elt
169
170 -- | List version of 'delFromFM'.
171 delListFromFM   :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [key] -> FiniteMap key elt
172
173 -- | Combine two 'FiniteMap's.  Mappings in the second argument shadow
174 -- those in the first.
175 plusFM          :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
176                            -> FiniteMap key elt
177
178 -- | Combine two 'FiniteMap's.  The specified combination function is
179 -- used to calculate the new value when there are two elements with
180 -- the same key.
181 plusFM_C        :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
182                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
183
184 -- | @(minusFM a1 a2)@ deletes from @a1@ any mappings which are bound in @a2@
185 minusFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt1 -> FiniteMap key elt2 -> FiniteMap key elt1
186
187 -- | @(intersectFM a1 a2)@ returns a new 'FiniteMap' containing
188 -- mappings from @a1@ for which @a2@ also has a mapping with the same
189 -- key.
190 intersectFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
191
192 -- | Returns the intersection of two mappings, using the specified
193 -- combination function to combine values.
194 intersectFM_C   :: (Ord key OUTPUTABLE_key) => (elt1 -> elt2 -> elt3)
195                            -> FiniteMap key elt1 -> FiniteMap key elt2 -> FiniteMap key elt3
196
197 --      MAPPING, FOLDING, FILTERING
198 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
199 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
200 filterFM        :: (Ord key OUTPUTABLE_key) => (key -> elt -> Bool)
201                            -> FiniteMap key elt -> FiniteMap key elt
202
203 --      INTERROGATING
204 sizeFM          :: FiniteMap key elt -> Int
205 isEmptyFM       :: FiniteMap key elt -> Bool
206
207 -- | Returns 'True' if the specified @key@ has a mapping in this
208 -- 'FiniteMap', or 'False' otherwise.
209 elemFM          :: (Ord key OUTPUTABLE_key) => key -> FiniteMap key elt -> Bool
210
211 -- | Looks up a key in a 'FiniteMap', returning @'Just' v@ if the key
212 -- was found with value @v@, or 'Nothing' otherwise.
213 lookupFM        :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> Maybe elt
214
215 -- | Looks up a key in a 'FiniteMap', returning @elt@ if the specified
216 -- @key@ was not found.
217 lookupWithDefaultFM
218                 :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> elt -> key -> elt
219                 -- lookupWithDefaultFM supplies a "default" elt
220                 -- to return for an unmapped key
221
222 --      LISTIFYING
223
224 -- | Convert a 'FiniteMap' to a @[(key, elt)]@ sorted by 'Ord' key
225 --
226 fmToList        :: FiniteMap key elt -> [(key,elt)]
227
228 -- | Extract the keys from a 'FiniteMap', in the order of the keys, so
229 --
230 -- > keysFM == map fst . fmToList
231 --
232 keysFM          :: FiniteMap key elt -> [key]
233
234 -- | Extract the elements from a 'FiniteMap', in the order of the keys, so
235 --
236 -- > eltsFM == map snd . fmToList
237 --
238 eltsFM          :: FiniteMap key elt -> [elt]
239
240 -- ---------------------------------------------------------------------------
241 -- The @FiniteMap@ data type, and building of same
242
243 -- Invariants about @FiniteMap@:
244 --
245 -- *  all keys in a FiniteMap are distinct
246 --
247 -- * all keys in left  subtree are $<$ key in Branch and
248 --   all keys in right subtree are $>$ key in Branch
249 -- 
250 -- * size field of a Branch gives number of Branch nodes in the tree
251 -- 
252 -- * size of left subtree is differs from size of right subtree by a
253 --   factor of at most \tr{sIZE_RATIO}
254
255 -- | A mapping from @key@s to @elt@s.
256 data FiniteMap key elt
257   = EmptyFM
258   | Branch key elt              -- Key and elt stored here
259     IF_GHC(Int#,Int{-STRICT-})  -- Size >= 1
260     (FiniteMap key elt)         -- Children
261     (FiniteMap key elt)
262
263
264 emptyFM = EmptyFM
265 {-
266 emptyFM
267   = Branch bottom bottom IF_GHC(0#,0) bottom bottom
268   where
269     bottom = panic "emptyFM"
270 -}
271
272 --  #define EmptyFM (Branch _ _ IF_GHC(0#,0) _ _)
273
274 unitFM key elt = Branch key elt IF_GHC(1#,1) emptyFM emptyFM
275
276 listToFM = addListToFM emptyFM
277
278 #ifdef COMPILING_GHC
279 bagToFM = foldBag plusFM (\ (k,v) -> unitFM k v) emptyFM
280 #endif
281
282 instance (Show k, Show e) => Show (FiniteMap k e) where
283   showsPrec p m = showsPrec p (fmToList m)
284
285 instance Functor (FiniteMap k) where
286   fmap f = mapFM (const f)
287
288 -- ---------------------------------------------------------------------------
289 -- Adding to and deleting from @FiniteMaps@
290
291 addToFM fm key elt = addToFM_C (\ old new -> new) fm key elt
292
293 addToFM_C combiner EmptyFM key elt = unitFM key elt
294 addToFM_C combiner (Branch key elt size fm_l fm_r) new_key new_elt
295 #ifdef __GLASGOW_HASKELL__
296   = case _tagCmp new_key key of
297         _LT -> mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
298         _GT -> mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
299         _EQ -> Branch new_key (combiner elt new_elt) size fm_l fm_r
300 #else
301   | new_key < key = mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
302   | new_key > key = mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
303   | otherwise     = Branch new_key (combiner elt new_elt) size fm_l fm_r
304 #endif
305
306 addListToFM fm key_elt_pairs = addListToFM_C (\ old new -> new) fm key_elt_pairs
307
308 addListToFM_C combiner fm key_elt_pairs
309   = foldl add fm key_elt_pairs  -- foldl adds from the left
310   where
311     add fmap (key,elt) = addToFM_C combiner fmap key elt
312
313
314 delFromFM EmptyFM del_key = emptyFM
315 delFromFM (Branch key elt size fm_l fm_r) del_key
316 #if __GLASGOW_HASKELL__
317   = case _tagCmp del_key key of
318         _GT -> mkBalBranch key elt fm_l (delFromFM fm_r del_key)
319         _LT -> mkBalBranch key elt (delFromFM fm_l del_key) fm_r
320         _EQ -> glueBal fm_l fm_r
321 #else
322   | del_key > key
323   = mkBalBranch key elt fm_l (delFromFM fm_r del_key)
324
325   | del_key < key
326   = mkBalBranch key elt (delFromFM fm_l del_key) fm_r
327
328   | key == del_key
329   = glueBal fm_l fm_r
330 #endif
331
332 delListFromFM fm keys = foldl delFromFM fm keys
333
334 -- ---------------------------------------------------------------------------
335 -- Combining @FiniteMaps@
336
337 plusFM_C combiner EmptyFM fm2 = fm2
338 plusFM_C combiner fm1 EmptyFM = fm1
339 plusFM_C combiner fm1 (Branch split_key elt2 _ left right)
340   = mkVBalBranch split_key new_elt
341                  (plusFM_C combiner lts left)
342                  (plusFM_C combiner gts right)
343   where
344     lts     = splitLT fm1 split_key
345     gts     = splitGT fm1 split_key
346     new_elt = case lookupFM fm1 split_key of
347                 Nothing   -> elt2
348                 Just elt1 -> combiner elt1 elt2
349
350 -- It's worth doing plusFM specially, because we don't need
351 -- to do the lookup in fm1.
352
353 plusFM EmptyFM fm2 = fm2
354 plusFM fm1 EmptyFM = fm1
355 plusFM fm1 (Branch split_key elt1 _ left right)
356   = mkVBalBranch split_key elt1 (plusFM lts left) (plusFM gts right)
357   where
358     lts     = splitLT fm1 split_key
359     gts     = splitGT fm1 split_key
360
361 minusFM EmptyFM fm2 = emptyFM
362 minusFM fm1 EmptyFM = fm1
363 minusFM fm1 (Branch split_key elt _ left right)
364   = glueVBal (minusFM lts left) (minusFM gts right)
365         -- The two can be way different, so we need glueVBal
366   where
367     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
368     gts = splitGT fm1 split_key         -- are not in either.
369
370 intersectFM fm1 fm2 = intersectFM_C (\ left right -> right) fm1 fm2
371
372 intersectFM_C combiner fm1 EmptyFM = emptyFM
373 intersectFM_C combiner EmptyFM fm2 = emptyFM
374 intersectFM_C combiner fm1 (Branch split_key elt2 _ left right)
375
376   | isJust maybe_elt1   -- split_elt *is* in intersection
377   = mkVBalBranch split_key (combiner elt1 elt2) (intersectFM_C combiner lts left)
378                                                 (intersectFM_C combiner gts right)
379
380   | otherwise                   -- split_elt is *not* in intersection
381   = glueVBal (intersectFM_C combiner lts left) (intersectFM_C combiner gts right)
382
383   where
384     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
385     gts = splitGT fm1 split_key         -- are not in either.
386
387     maybe_elt1 = lookupFM fm1 split_key
388     Just elt1  = maybe_elt1
389
390
391 -- ---------------------------------------------------------------------------
392 -- Mapping, folding, and filtering with @FiniteMaps@
393
394 foldFM k z EmptyFM = z
395 foldFM k z (Branch key elt _ fm_l fm_r)
396   = foldFM k (k key elt (foldFM k z fm_r)) fm_l
397
398 mapFM f EmptyFM = emptyFM
399 mapFM f (Branch key elt size fm_l fm_r)
400   = Branch key (f key elt) size (mapFM f fm_l) (mapFM f fm_r)
401
402 filterFM p EmptyFM = emptyFM
403 filterFM p (Branch key elt _ fm_l fm_r)
404   | p key elt           -- Keep the item
405   = mkVBalBranch key elt (filterFM p fm_l) (filterFM p fm_r)
406
407   | otherwise           -- Drop the item
408   = glueVBal (filterFM p fm_l) (filterFM p fm_r)
409
410
411 -- ---------------------------------------------------------------------------
412 -- Interrogating @FiniteMaps@
413
414 --{-# INLINE sizeFM #-}
415 sizeFM EmptyFM               = 0
416 sizeFM (Branch _ _ size _ _) = IF_GHC(I# size, size)
417
418 isEmptyFM fm = sizeFM fm == 0
419
420 lookupFM EmptyFM key = Nothing
421 lookupFM (Branch key elt _ fm_l fm_r) key_to_find
422 #if __GLASGOW_HASKELL__
423   = case _tagCmp key_to_find key of
424         _LT -> lookupFM fm_l key_to_find
425         _GT -> lookupFM fm_r key_to_find
426         _EQ -> Just elt
427 #else
428   | key_to_find < key = lookupFM fm_l key_to_find
429   | key_to_find > key = lookupFM fm_r key_to_find
430   | otherwise     = Just elt
431 #endif
432
433 key `elemFM` fm
434   = case (lookupFM fm key) of { Nothing -> False; Just elt -> True }
435
436 lookupWithDefaultFM fm deflt key
437   = case (lookupFM fm key) of { Nothing -> deflt; Just elt -> elt }
438
439
440 -- ---------------------------------------------------------------------------
441 -- Listifying @FiniteMaps@
442
443 fmToList fm = foldFM (\ key elt rest -> (key,elt) : rest) [] fm
444 keysFM fm   = foldFM (\ key elt rest -> key : rest)       [] fm
445 eltsFM fm   = foldFM (\ key elt rest -> elt : rest)       [] fm
446
447
448 -- ---------------------------------------------------------------------------
449 -- Bulk operations on all keys >= or <= a certain threshold
450
451 -- | Fold through all elements greater than or equal to the supplied key,
452 -- in increasing order.
453 foldFM_GE       :: Ord key => (key -> elt -> a -> a) -> a -> key ->
454    FiniteMap key elt -> a
455
456 foldFM_GE k z fr EmptyFM = z
457 foldFM_GE k z fr (Branch key elt _ fm_l fm_r)
458   | key >= fr = foldFM_GE k (k key elt (foldFM_GE k z fr fm_r)) fr fm_l
459   | otherwise = foldFM_GE k z fr fm_r
460
461 -- | List elements greater than or equal to the supplied key, in increasing
462 -- order
463 fmToList_GE      :: Ord key => FiniteMap key elt -> key ->  [(key,elt)]
464 fmToList_GE fm fr = foldFM_GE (\ key elt rest -> (key,elt) : rest) [] fr fm
465
466 -- | List keys greater than or equal to the supplied key, in increasing order
467 keysFM_GE       :: Ord key => FiniteMap key elt -> key -> [key]
468 keysFM_GE fm fr  = foldFM_GE (\ key elt rest -> key : rest)       [] fr fm
469
470 -- | List elements corresponding to keys greater than or equal to the supplied
471 -- key, in increasing order of key.
472 eltsFM_GE       :: Ord key => FiniteMap key elt -> key -> [elt]
473 eltsFM_GE fm fr  = foldFM_GE (\ key elt rest -> elt : rest)       [] fr fm
474
475 -- | Fold through all elements less than or equal to the supplied key,
476 -- in decreasing order.
477 foldFM_LE       :: Ord key => (key -> elt -> a -> a) -> a -> key ->
478    FiniteMap key elt -> a
479 foldFM_LE k z fr EmptyFM = z
480 foldFM_LE k z fr (Branch key elt _ fm_l fm_r)
481   | key <= fr = foldFM_LE k (k key elt (foldFM_LE k z fr fm_l)) fr fm_r
482   | otherwise = foldFM_LE k z fr fm_l
483
484 -- | List elements greater than or equal to the supplied key, in decreasing
485 -- order
486 fmToList_LE      :: Ord key => FiniteMap key elt -> key ->  [(key,elt)]
487 fmToList_LE fm fr = foldFM_LE (\ key elt rest -> (key,elt) : rest) [] fr fm
488
489 -- | List keys greater than or equal to the supplied key, in decreasing order
490 keysFM_LE       :: Ord key => FiniteMap key elt -> key -> [key]
491 keysFM_LE fm fr  = foldFM_LE (\ key elt rest -> key : rest)       [] fr fm
492
493 -- | List elements corresponding to keys greater than or equal to the supplied
494 -- key, in decreasing order of key.
495 eltsFM_LE       :: Ord key => FiniteMap key elt -> key -> [elt]
496 eltsFM_LE fm fr  = foldFM_LE (\ key elt rest -> elt : rest)       [] fr fm
497
498 -- ---------------------------------------------------------------------------
499 -- Getting minimum and maximum key out.
500 -- ---------------------------------------------------------------------------
501
502 -- | Extract minimum key, or Nothing if the map is empty.
503 minFM :: Ord key => FiniteMap key elt -> Maybe key
504 minFM EmptyFM = Nothing
505 minFM (Branch key _ _ fm_l _) =
506    case minFM fm_l of
507       Nothing -> Just key
508       Just key1 -> Just key1
509
510 -- | Extract maximum key, or Nothing if the map is empty.
511 maxFM :: Ord key => FiniteMap key elt -> Maybe key
512 maxFM EmptyFM = Nothing
513 maxFM (Branch key _ _ _ fm_r) =
514    case maxFM fm_r of
515       Nothing -> Just key
516       Just key1 -> Just key1
517
518
519 -- ---------------------------------------------------------------------------
520 -- The implementation of balancing
521
522 -- Basic construction of a @FiniteMap@:
523
524 -- @mkBranch@ simply gets the size component right.  This is the ONLY
525 -- (non-trivial) place the Branch object is built, so the ASSERTion
526 -- recursively checks consistency.  (The trivial use of Branch is in
527 -- @unitFM@.)
528
529 sIZE_RATIO :: Int
530 sIZE_RATIO = 5
531
532 mkBranch :: (Ord key OUTPUTABLE_key)            -- Used for the assertion checking only
533          => Int
534          -> key -> elt
535          -> FiniteMap key elt -> FiniteMap key elt
536          -> FiniteMap key elt
537
538 mkBranch which key elt fm_l fm_r
539   = --ASSERT( left_ok && right_ok && balance_ok )
540 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
541     if not ( left_ok && right_ok && balance_ok ) then
542         pprPanic ("mkBranch:"++show which) (ppAboves [ppr PprDebug [left_ok, right_ok, balance_ok],
543                                        ppr PprDebug key,
544                                        ppr PprDebug fm_l,
545                                        ppr PprDebug fm_r])
546     else
547 #endif
548     let
549         result = Branch key elt (unbox (1 + left_size + right_size)) fm_l fm_r
550     in
551 --    if sizeFM result <= 8 then
552         result
553 --    else
554 --      pprTrace ("mkBranch:"++(show which)) (ppr PprDebug result) (
555 --      result
556 --      )
557   where
558     left_ok  = case fm_l of
559                 EmptyFM                  -> True
560                 Branch left_key _ _ _ _  -> let
561                                                 biggest_left_key = fst (findMax fm_l)
562                                             in
563                                             biggest_left_key < key
564     right_ok = case fm_r of
565                 EmptyFM                  -> True
566                 Branch right_key _ _ _ _ -> let
567                                                 smallest_right_key = fst (findMin fm_r)
568                                             in
569                                             key < smallest_right_key
570     balance_ok = True -- sigh
571 {- LATER:
572     balance_ok
573       = -- Both subtrees have one or no elements...
574         (left_size + right_size <= 1)
575 -- NO         || left_size == 0  -- ???
576 -- NO         || right_size == 0 -- ???
577         -- ... or the number of elements in a subtree does not exceed
578         -- sIZE_RATIO times the number of elements in the other subtree
579       || (left_size  * sIZE_RATIO >= right_size &&
580           right_size * sIZE_RATIO >= left_size)
581 -}
582
583     left_size  = sizeFM fm_l
584     right_size = sizeFM fm_r
585
586 #if __GLASGOW_HASKELL__
587     unbox :: Int -> Int#
588     unbox (I# size) = size
589 #else
590     unbox :: Int -> Int
591     unbox x = x
592 #endif
593
594
595 -- ---------------------------------------------------------------------------
596 -- {\em Balanced} construction of a @FiniteMap@
597
598 -- @mkBalBranch@ rebalances, assuming that the subtrees aren't too far
599 -- out of whack.
600
601 mkBalBranch :: (Ord key OUTPUTABLE_key)
602             => key -> elt
603             -> FiniteMap key elt -> FiniteMap key elt
604             -> FiniteMap key elt
605
606 mkBalBranch key elt fm_L fm_R
607
608   | size_l + size_r < 2
609   = mkBranch 1{-which-} key elt fm_L fm_R
610
611   | size_r > sIZE_RATIO * size_l        -- Right tree too big
612   = case fm_R of
613         Branch _ _ _ fm_rl fm_rr
614                 | sizeFM fm_rl < 2 * sizeFM fm_rr -> single_L fm_L fm_R
615                 | otherwise                       -> double_L fm_L fm_R
616         -- Other case impossible
617
618   | size_l > sIZE_RATIO * size_r        -- Left tree too big
619   = case fm_L of
620         Branch _ _ _ fm_ll fm_lr
621                 | sizeFM fm_lr < 2 * sizeFM fm_ll -> single_R fm_L fm_R
622                 | otherwise                       -> double_R fm_L fm_R
623         -- Other case impossible
624
625   | otherwise                           -- No imbalance
626   = mkBranch 2{-which-} key elt fm_L fm_R
627
628   where
629     size_l   = sizeFM fm_L
630     size_r   = sizeFM fm_R
631
632     single_L fm_l (Branch key_r elt_r _ fm_rl fm_rr)
633         = mkBranch 3{-which-} key_r elt_r (mkBranch 4{-which-} key elt fm_l fm_rl) fm_rr
634
635     double_L fm_l (Branch key_r elt_r _ (Branch key_rl elt_rl _ fm_rll fm_rlr) fm_rr)
636         = mkBranch 5{-which-} key_rl elt_rl (mkBranch 6{-which-} key   elt   fm_l   fm_rll)
637                                  (mkBranch 7{-which-} key_r elt_r fm_rlr fm_rr)
638
639     single_R (Branch key_l elt_l _ fm_ll fm_lr) fm_r
640         = mkBranch 8{-which-} key_l elt_l fm_ll (mkBranch 9{-which-} key elt fm_lr fm_r)
641
642     double_R (Branch key_l elt_l _ fm_ll (Branch key_lr elt_lr _ fm_lrl fm_lrr)) fm_r
643         = mkBranch 10{-which-} key_lr elt_lr (mkBranch 11{-which-} key_l elt_l fm_ll  fm_lrl)
644                                  (mkBranch 12{-which-} key   elt   fm_lrr fm_r)
645
646
647 mkVBalBranch :: (Ord key OUTPUTABLE_key)
648              => key -> elt
649              -> FiniteMap key elt -> FiniteMap key elt
650              -> FiniteMap key elt
651
652 -- Assert: in any call to (mkVBalBranch_C comb key elt l r),
653 --         (a) all keys in l are < all keys in r
654 --         (b) all keys in l are < key
655 --         (c) all keys in r are > key
656
657 mkVBalBranch key elt EmptyFM fm_r = addToFM fm_r key elt
658 mkVBalBranch key elt fm_l EmptyFM = addToFM fm_l key elt
659
660 mkVBalBranch key elt fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
661                      fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
662   | sIZE_RATIO * size_l < size_r
663   = mkBalBranch key_r elt_r (mkVBalBranch key elt fm_l fm_rl) fm_rr
664
665   | sIZE_RATIO * size_r < size_l
666   = mkBalBranch key_l elt_l fm_ll (mkVBalBranch key elt fm_lr fm_r)
667
668   | otherwise
669   = mkBranch 13{-which-} key elt fm_l fm_r
670
671   where
672     size_l = sizeFM fm_l
673     size_r = sizeFM fm_r
674
675 -- ---------------------------------------------------------------------------
676 -- Gluing two trees together
677
678 -- @glueBal@ assumes its two arguments aren't too far out of whack, just
679 -- like @mkBalBranch@.  But: all keys in first arg are $<$ all keys in
680 -- second.
681
682 glueBal :: (Ord key OUTPUTABLE_key)
683         => FiniteMap key elt -> FiniteMap key elt
684         -> FiniteMap key elt
685
686 glueBal EmptyFM fm2 = fm2
687 glueBal fm1 EmptyFM = fm1
688 glueBal fm1 fm2
689         -- The case analysis here (absent in Adams' program) is really to deal
690         -- with the case where fm2 is a singleton. Then deleting the minimum means
691         -- we pass an empty tree to mkBalBranch, which breaks its invariant.
692   | sizeFM fm2 > sizeFM fm1
693   = mkBalBranch mid_key2 mid_elt2 fm1 (deleteMin fm2)
694
695   | otherwise
696   = mkBalBranch mid_key1 mid_elt1 (deleteMax fm1) fm2
697   where
698     (mid_key1, mid_elt1) = findMax fm1
699     (mid_key2, mid_elt2) = findMin fm2
700
701 -- @glueVBal@ copes with arguments which can be of any size.
702 -- But: all keys in first arg are $<$ all keys in second.
703
704 glueVBal :: (Ord key OUTPUTABLE_key)
705          => FiniteMap key elt -> FiniteMap key elt
706          -> FiniteMap key elt
707
708 glueVBal EmptyFM fm2 = fm2
709 glueVBal fm1 EmptyFM = fm1
710 glueVBal fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
711          fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
712   | sIZE_RATIO * size_l < size_r
713   = mkBalBranch key_r elt_r (glueVBal fm_l fm_rl) fm_rr
714
715   | sIZE_RATIO * size_r < size_l
716   = mkBalBranch key_l elt_l fm_ll (glueVBal fm_lr fm_r)
717
718   | otherwise           -- We now need the same two cases as in glueBal above.
719   = glueBal fm_l fm_r
720   where
721     size_l = sizeFM fm_l
722     size_r = sizeFM fm_r
723
724
725 -- ---------------------------------------------------------------------------
726 -- Local utilities
727
728 splitLT, splitGT :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> FiniteMap key elt
729
730 -- splitLT fm split_key  =  fm restricted to keys <  split_key
731 -- splitGT fm split_key  =  fm restricted to keys >  split_key
732
733 splitLT EmptyFM split_key = emptyFM
734 splitLT (Branch key elt _ fm_l fm_r) split_key
735 #if __GLASGOW_HASKELL__
736   = case _tagCmp split_key key of
737         _LT -> splitLT fm_l split_key
738         _GT -> mkVBalBranch key elt fm_l (splitLT fm_r split_key)
739         _EQ -> fm_l
740 #else
741   | split_key < key = splitLT fm_l split_key
742   | split_key > key = mkVBalBranch key elt fm_l (splitLT fm_r split_key)
743   | otherwise       = fm_l
744 #endif
745
746 splitGT EmptyFM split_key = emptyFM
747 splitGT (Branch key elt _ fm_l fm_r) split_key
748 #if __GLASGOW_HASKELL__
749   = case _tagCmp split_key key of
750         _GT -> splitGT fm_r split_key
751         _LT -> mkVBalBranch key elt (splitGT fm_l split_key) fm_r
752         _EQ -> fm_r
753 #else
754   | split_key > key = splitGT fm_r split_key
755   | split_key < key = mkVBalBranch key elt (splitGT fm_l split_key) fm_r
756   | otherwise       = fm_r
757 #endif
758
759 findMin :: FiniteMap key elt -> (key,elt)
760 findMin (Branch key elt _ EmptyFM _) = (key,elt)
761 findMin (Branch key elt _ fm_l    _) = findMin fm_l
762
763 deleteMin :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
764 deleteMin (Branch key elt _ EmptyFM fm_r) = fm_r
765 deleteMin (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt (deleteMin fm_l) fm_r
766
767 findMax :: FiniteMap key elt -> (key,elt)
768 findMax (Branch key elt _ _ EmptyFM) = (key,elt)
769 findMax (Branch key elt _ _    fm_r) = findMax fm_r
770
771 deleteMax :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
772 deleteMax (Branch key elt _ fm_l EmptyFM) = fm_l
773 deleteMax (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt fm_l (deleteMax fm_r)
774
775
776 -- ---------------------------------------------------------------------------
777 -- Output-ery
778
779 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
780
781 instance (Outputable key) => Outputable (FiniteMap key elt) where
782     ppr sty fm = pprX sty fm
783
784 pprX sty EmptyFM = ppChar '!'
785 pprX sty (Branch key elt sz fm_l fm_r)
786  = ppBesides [ppLparen, pprX sty fm_l, ppSP,
787               ppr sty key, ppSP, ppInt (IF_GHC(I# sz, sz)), ppSP,
788               pprX sty fm_r, ppRparen]
789 #endif
790
791 #ifndef COMPILING_GHC
792 instance (Eq key, Eq elt) => Eq (FiniteMap key elt) where
793   fm_1 == fm_2 = (sizeFM   fm_1 == sizeFM   fm_2) &&   -- quick test
794                  (fmToList fm_1 == fmToList fm_2)
795
796 {- NO: not clear what The Right Thing to do is:
797 instance (Ord key, Ord elt) => Ord (FiniteMap key elt) where
798   fm_1 <= fm_2 = (sizeFM   fm_1 <= sizeFM   fm_2) &&   -- quick test
799                  (fmToList fm_1 <= fmToList fm_2)
800 -}
801 #endif
802
803 -- ---------------------------------------------------------------------------
804 -- Efficiency pragmas for GHC
805
806 -- When the FiniteMap module is used in GHC, we specialise it for
807 -- \tr{Uniques}, for dastardly efficiency reasons.
808
809 #if defined(COMPILING_GHC) && __GLASGOW_HASKELL__ && !defined(REALLY_HASKELL_1_3)
810
811 {-# SPECIALIZE addListToFM
812                 :: FiniteMap (FAST_STRING, FAST_STRING) elt -> [((FAST_STRING, FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
813                  , FiniteMap RdrName elt -> [(RdrName,elt)] -> FiniteMap RdrName elt
814     IF_NCG(COMMA   FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
815     #-}
816 {-# SPECIALIZE addListToFM_C
817                 :: (elt -> elt -> elt) -> FiniteMap TyCon elt -> [(TyCon,elt)] -> FiniteMap TyCon elt
818                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
819     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
820     #-}
821 {-# SPECIALIZE addToFM
822                 :: FiniteMap CLabel elt -> CLabel -> elt  -> FiniteMap CLabel elt
823                  , FiniteMap FAST_STRING elt -> FAST_STRING -> elt  -> FiniteMap FAST_STRING elt
824                  , FiniteMap (FAST_STRING, FAST_STRING) elt -> (FAST_STRING, FAST_STRING) -> elt  -> FiniteMap (FAST_STRING, FAST_STRING) elt
825                  , FiniteMap RdrName elt -> RdrName -> elt  -> FiniteMap RdrName elt
826                  , FiniteMap OrigName elt -> OrigName -> elt  -> FiniteMap OrigName elt
827     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> elt  -> FiniteMap Reg elt)
828     #-}
829 {-# SPECIALIZE addToFM_C
830                 :: (elt -> elt -> elt) -> FiniteMap (RdrName, RdrName) elt -> (RdrName, RdrName) -> elt -> FiniteMap (RdrName, RdrName) elt
831                  , (elt -> elt -> elt) -> FiniteMap (OrigName, OrigName) elt -> (OrigName, OrigName) -> elt -> FiniteMap (OrigName, OrigName) elt
832                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FAST_STRING -> elt -> FiniteMap FAST_STRING elt
833     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> Reg -> elt -> FiniteMap Reg elt)
834     #-}
835 {-# SPECIALIZE bagToFM
836                 :: Bag (FAST_STRING,elt) -> FiniteMap FAST_STRING elt
837     #-}
838 {-# SPECIALIZE delListFromFM
839                 :: FiniteMap RdrName elt -> [RdrName]   -> FiniteMap RdrName elt
840                  , FiniteMap OrigName elt -> [OrigName]   -> FiniteMap OrigName elt
841                  , FiniteMap FAST_STRING elt -> [FAST_STRING]   -> FiniteMap FAST_STRING elt
842     IF_NCG(COMMA   FiniteMap Reg elt -> [Reg]   -> FiniteMap Reg elt)
843     #-}
844 {-# SPECIALIZE listToFM
845                 :: [([Char],elt)] -> FiniteMap [Char] elt
846                  , [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
847                  , [((FAST_STRING,FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
848                  , [(OrigName,elt)] -> FiniteMap OrigName elt
849     IF_NCG(COMMA   [(Reg COMMA elt)] -> FiniteMap Reg elt)
850     #-}
851 {-# SPECIALIZE lookupFM
852                 :: FiniteMap CLabel elt -> CLabel -> Maybe elt
853                  , FiniteMap [Char] elt -> [Char] -> Maybe elt
854                  , FiniteMap FAST_STRING elt -> FAST_STRING -> Maybe elt
855                  , FiniteMap (FAST_STRING,FAST_STRING) elt -> (FAST_STRING,FAST_STRING) -> Maybe elt
856                  , FiniteMap OrigName elt -> OrigName -> Maybe elt
857                  , FiniteMap (OrigName,OrigName) elt -> (OrigName,OrigName) -> Maybe elt
858                  , FiniteMap RdrName elt -> RdrName -> Maybe elt
859                  , FiniteMap (RdrName,RdrName) elt -> (RdrName,RdrName) -> Maybe elt
860     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> Maybe elt)
861     #-}
862 {-# SPECIALIZE lookupWithDefaultFM
863                 :: FiniteMap FAST_STRING elt -> elt -> FAST_STRING -> elt
864     IF_NCG(COMMA   FiniteMap Reg elt -> elt -> Reg -> elt)
865     #-}
866 {-# SPECIALIZE plusFM
867                 :: FiniteMap RdrName elt -> FiniteMap RdrName elt -> FiniteMap RdrName elt
868                  , FiniteMap OrigName elt -> FiniteMap OrigName elt -> FiniteMap OrigName elt
869                  , FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
870     IF_NCG(COMMA   FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
871     #-}
872 {-# SPECIALIZE plusFM_C
873                 :: (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
874     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
875     #-}
876
877 #endif /* compiling for GHC */