remove empty dir
[ghc-hetmet.git] / ghc / compiler / utils / ListSetOps.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[ListSetOps]{Set-like operations on lists}
5
6 \begin{code}
7 module ListSetOps (
8         unionLists, minusList, insertList,
9
10         -- Association lists
11         Assoc, assoc, assocMaybe, assocUsing, assocDefault, assocDefaultUsing,
12         emptyAssoc, unitAssoc, mapAssoc, plusAssoc_C, extendAssoc_C,
13         mkLookupFun, findInList, assocElts,
14
15         -- Duplicate handling
16         hasNoDups, runs, removeDups, findDupsEq, 
17         equivClasses, equivClassesByUniq
18
19    ) where
20
21 #include "HsVersions.h"
22
23 import Outputable
24 import Unique   ( Unique )
25 import UniqFM   ( eltsUFM, emptyUFM, addToUFM_C )
26 import Util     ( isn'tIn, isIn, mapAccumR, sortLe )
27 import List     ( partition )
28 \end{code}
29
30
31 %************************************************************************
32 %*                                                                      *
33         Treating lists as sets
34         Assumes the lists contain no duplicates, but are unordered
35 %*                                                                      *
36 %************************************************************************
37
38 \begin{code}
39 insertList :: Eq a => a -> [a] -> [a]
40 -- Assumes the arg list contains no dups; guarantees the result has no dups
41 insertList x xs | isIn "insert" x xs = xs
42             | otherwise          = x : xs
43
44 unionLists :: (Eq a) => [a] -> [a] -> [a]
45 -- Assumes that the arguments contain no duplicates
46 unionLists xs ys = [x | x <- xs, isn'tIn "unionLists" x ys] ++ ys
47
48 minusList :: (Eq a) => [a] -> [a] -> [a]
49 -- Everything in the first list that is not in the second list:
50 minusList xs ys = [ x | x <- xs, isn'tIn "minusList" x ys]
51 \end{code}
52
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection[Utils-assoc]{Association lists}
57 %*                                                                      *
58 %************************************************************************
59
60 Inefficient finite maps based on association lists and equality.
61
62 \begin{code}
63 type Assoc a b = [(a,b)]        -- A finite mapping based on equality and association lists
64
65 emptyAssoc        :: Assoc a b
66 unitAssoc         :: a -> b -> Assoc a b
67 assocElts         :: Assoc a b -> [(a,b)]
68 assoc             :: (Eq a) => String -> Assoc a b -> a -> b
69 assocDefault      :: (Eq a) => b -> Assoc a b -> a -> b
70 assocUsing        :: (a -> a -> Bool) -> String -> Assoc a b -> a -> b
71 assocMaybe        :: (Eq a) => Assoc a b -> a -> Maybe b
72 assocDefaultUsing :: (a -> a -> Bool) -> b -> Assoc a b -> a -> b
73 mapAssoc          :: (b -> c) -> Assoc a b -> Assoc a c
74 extendAssoc_C     :: (Eq a) => (b -> b -> b) -> Assoc a b -> (a,b)     -> Assoc a b
75 plusAssoc_C       :: (Eq a) => (b -> b -> b) -> Assoc a b -> Assoc a b -> Assoc a b
76         -- combining fn takes (old->new->result)
77
78 emptyAssoc    = []
79 unitAssoc a b = [(a,b)]
80 assocElts xs  = xs
81
82 assocDefaultUsing eq deflt ((k,v) : rest) key
83   | k `eq` key = v
84   | otherwise  = assocDefaultUsing eq deflt rest key
85
86 assocDefaultUsing eq deflt [] key = deflt
87
88 assoc crash_msg         list key = assocDefaultUsing (==) (panic ("Failed in assoc: " ++ crash_msg)) list key
89 assocDefault deflt      list key = assocDefaultUsing (==) deflt list key
90 assocUsing eq crash_msg list key = assocDefaultUsing eq (panic ("Failed in assoc: " ++ crash_msg)) list key
91
92 assocMaybe alist key
93   = lookup alist
94   where
95     lookup []             = Nothing
96     lookup ((tv,ty):rest) = if key == tv then Just ty else lookup rest
97
98 mapAssoc f alist = [(key, f val) | (key,val) <- alist]
99
100 plusAssoc_C combine []  new = new       -- Shortcut for common case
101 plusAssoc_C combine old new = foldl (extendAssoc_C combine) old new
102
103 extendAssoc_C combine old_list (new_key, new_val)
104   = go old_list
105   where
106     go [] = [(new_key, new_val)]
107     go ((old_key, old_val) : old_list) 
108         | new_key == old_key = ((old_key, old_val `combine` new_val) : old_list)
109         | otherwise          = (old_key, old_val) : go old_list
110 \end{code}
111
112
113 @mkLookupFun eq alist@ is a function which looks up
114 its argument in the association list @alist@, returning a Maybe type.
115 @mkLookupFunDef@ is similar except that it is given a value to return
116 on failure.
117
118 \begin{code}
119 mkLookupFun :: (key -> key -> Bool)     -- Equality predicate
120             -> [(key,val)]              -- The assoc list
121             -> key                      -- The key
122             -> Maybe val                -- The corresponding value
123
124 mkLookupFun eq alist s
125   = case [a | (s',a) <- alist, s' `eq` s] of
126       []    -> Nothing
127       (a:_) -> Just a
128
129 findInList :: (a -> Bool) -> [a] -> Maybe a
130 findInList p [] = Nothing
131 findInList p (x:xs) | p x       = Just x
132                     | otherwise = findInList p xs
133 \end{code}
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection[Utils-dups]{Duplicate-handling}
139 %*                                                                      *
140 %************************************************************************
141
142 \begin{code}
143 hasNoDups :: (Eq a) => [a] -> Bool
144
145 hasNoDups xs = f [] xs
146   where
147     f seen_so_far []     = True
148     f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
149                                 False
150                            else
151                                 f (x:seen_so_far) xs
152
153     is_elem = isIn "hasNoDups"
154 \end{code}
155
156 \begin{code}
157 equivClasses :: (a -> a -> Ordering)    -- Comparison
158              -> [a]
159              -> [[a]]
160
161 equivClasses cmp stuff@[]     = []
162 equivClasses cmp stuff@[item] = [stuff]
163 equivClasses cmp items
164   = runs eq (sortLe le items)
165   where
166     eq a b = case cmp a b of { EQ -> True; _ -> False }
167     le a b = case cmp a b of { LT -> True; EQ -> True; GT -> False }
168 \end{code}
169
170 The first cases in @equivClasses@ above are just to cut to the point
171 more quickly...
172
173 @runs@ groups a list into a list of lists, each sublist being a run of
174 identical elements of the input list. It is passed a predicate @p@ which
175 tells when two elements are equal.
176
177 \begin{code}
178 runs :: (a -> a -> Bool)        -- Equality
179      -> [a]
180      -> [[a]]
181
182 runs p []     = []
183 runs p (x:xs) = case (span (p x) xs) of
184                   (first, rest) -> (x:first) : (runs p rest)
185 \end{code}
186
187 \begin{code}
188 removeDups :: (a -> a -> Ordering)      -- Comparison function
189            -> [a]
190            -> ([a],     -- List with no duplicates
191                [[a]])   -- List of duplicate groups.  One representative from
192                         -- each group appears in the first result
193
194 removeDups cmp []  = ([], [])
195 removeDups cmp [x] = ([x],[])
196 removeDups cmp xs
197   = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
198     (xs', dups) }
199   where
200     collect_dups dups_so_far [x]         = (dups_so_far,      x)
201     collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
202
203 findDupsEq :: (a->a->Bool) -> [a] -> [[a]]
204 findDupsEq eq [] = []
205 findDupsEq eq (x:xs) | null eq_xs  = findDupsEq eq xs
206                      | otherwise   = (x:eq_xs) : findDupsEq eq neq_xs
207                      where
208                        (eq_xs, neq_xs) = partition (eq x) xs
209 \end{code}
210
211
212 \begin{code}
213 equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]]
214         -- NB: it's *very* important that if we have the input list [a,b,c],
215         -- where a,b,c all have the same unique, then we get back the list
216         --      [a,b,c]
217         -- not
218         --      [c,b,a]
219         -- Hence the use of foldr, plus the reversed-args tack_on below
220 equivClassesByUniq get_uniq xs
221   = eltsUFM (foldr add emptyUFM xs)
222   where
223     add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a]
224     tack_on old new = new++old
225 \end{code}
226
227