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