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