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