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