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