[project @ 1998-12-18 17:40:31 by simonpj]
[ghc-hetmet.git] / ghc / compiler / utils / Util.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Util]{Highly random utility functions}
5
6 \begin{code}
7 -- IF_NOT_GHC is meant to make this module useful outside the context of GHC
8 #define IF_NOT_GHC(a)
9
10 module Util (
11         -- The Eager monad
12         Eager, thenEager, returnEager, mapEager, appEager, runEager,
13
14         -- general list processing
15         IF_NOT_GHC(forall COMMA exists COMMA)
16         zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
17         zipLazy, stretchZipEqual,
18         mapAndUnzip, mapAndUnzip3,
19         nOfThem, lengthExceeds, isSingleton,
20         snocView,
21         isIn, isn'tIn,
22
23         -- association lists
24         assoc, assocUsing, assocDefault, assocDefaultUsing,
25
26         -- duplicate handling
27         hasNoDups, equivClasses, runs, removeDups, equivClassesByUniq,
28
29         -- sorting
30         IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
31         sortLt,
32         IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
33         IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
34
35         -- transitive closures
36         transitiveClosure,
37
38         -- accumulating
39         mapAccumL, mapAccumR, mapAccumB,
40
41         -- comparisons
42         thenCmp, cmpList,
43
44         -- pairs
45         IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
46         IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
47         unzipWith
48     ) where
49
50 #include "HsVersions.h"
51
52 import List             ( zipWith4 )
53 import Panic            ( panic )
54 import Unique           ( Unique )
55 import UniqFM           ( eltsUFM, emptyUFM, addToUFM_C )
56
57 infixr 9 `thenCmp`
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{The Eager monad}
63 %*                                                                      *
64 %************************************************************************
65
66 The @Eager@ monad is just an encoding of continuation-passing style,
67 used to allow you to express "do this and then that", mainly to avoid
68 space leaks. It's done with a type synonym to save bureaucracy.
69
70 \begin{code}
71 type Eager ans a = (a -> ans) -> ans
72
73 runEager :: Eager a a -> a
74 runEager m = m (\x -> x)
75
76 appEager :: Eager ans a -> (a -> ans) -> ans
77 appEager m cont = m cont
78
79 thenEager :: Eager ans a -> (a -> Eager ans b) -> Eager ans b
80 thenEager m k cont = m (\r -> k r cont)
81
82 returnEager :: a -> Eager ans a
83 returnEager v cont = cont v
84
85 mapEager :: (a -> Eager ans b) -> [a] -> Eager ans [b]
86 mapEager f [] = returnEager []
87 mapEager f (x:xs) = f x                 `thenEager` \ y ->
88                     mapEager f xs       `thenEager` \ ys ->
89                     returnEager (y:ys)
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection[Utils-lists]{General list processing}
95 %*                                                                      *
96 %************************************************************************
97
98 Quantifiers are not standard in Haskell. The following fill in the gap.
99
100 \begin{code}
101 forall :: (a -> Bool) -> [a] -> Bool
102 forall pred []     = True
103 forall pred (x:xs) = pred x && forall pred xs
104
105 exists :: (a -> Bool) -> [a] -> Bool
106 exists pred []     = False
107 exists pred (x:xs) = pred x || exists pred xs
108 \end{code}
109
110 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
111 are of equal length.  Alastair Reid thinks this should only happen if
112 DEBUGging on; hey, why not?
113
114 \begin{code}
115 zipEqual        :: String -> [a] -> [b] -> [(a,b)]
116 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
117 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
118 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
119
120 #ifndef DEBUG
121 zipEqual      _ = zip
122 zipWithEqual  _ = zipWith
123 zipWith3Equal _ = zipWith3
124 zipWith4Equal _ = zipWith4
125 #else
126 zipEqual msg []     []     = []
127 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
128 zipEqual msg as     bs     = panic ("zipEqual: unequal lists:"++msg)
129
130 zipWithEqual msg z (a:as) (b:bs)=  z a b : zipWithEqual msg z as bs
131 zipWithEqual msg _ [] []        =  []
132 zipWithEqual msg _ _ _          =  panic ("zipWithEqual: unequal lists:"++msg)
133
134 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
135                                 =  z a b c : zipWith3Equal msg z as bs cs
136 zipWith3Equal msg _ [] []  []   =  []
137 zipWith3Equal msg _ _  _   _    =  panic ("zipWith3Equal: unequal lists:"++msg)
138
139 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
140                                 =  z a b c d : zipWith4Equal msg z as bs cs ds
141 zipWith4Equal msg _ [] [] [] [] =  []
142 zipWith4Equal msg _ _  _  _  _  =  panic ("zipWith4Equal: unequal lists:"++msg)
143 #endif
144 \end{code}
145
146 \begin{code}
147 -- zipLazy is lazy in the second list (observe the ~)
148
149 zipLazy :: [a] -> [b] -> [(a,b)]
150 zipLazy [] ys = []
151 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
152 \end{code}
153
154
155 \begin{code}
156 stretchZipEqual :: (a -> b -> Maybe a) -> [a] -> [b] -> [a]
157 -- (stretchZipEqual f xs ys) stretches ys to "fit" the places where f returns a Just
158
159 stretchZipEqual f [] [] = []
160 stretchZipEqual f (x:xs) (y:ys) = case f x y of
161                                     Just x' -> x' : stretchZipEqual f xs ys
162                                     Nothing -> x  :  stretchZipEqual f xs (y:ys)
163 \end{code}
164
165
166 \begin{code}
167 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
168
169 mapAndUnzip f [] = ([],[])
170 mapAndUnzip f (x:xs)
171   = let
172         (r1,  r2)  = f x
173         (rs1, rs2) = mapAndUnzip f xs
174     in
175     (r1:rs1, r2:rs2)
176
177 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
178
179 mapAndUnzip3 f [] = ([],[],[])
180 mapAndUnzip3 f (x:xs)
181   = let
182         (r1,  r2,  r3)  = f x
183         (rs1, rs2, rs3) = mapAndUnzip3 f xs
184     in
185     (r1:rs1, r2:rs2, r3:rs3)
186 \end{code}
187
188 \begin{code}
189 nOfThem :: Int -> a -> [a]
190 nOfThem n thing = take n (repeat thing)
191
192 lengthExceeds :: [a] -> Int -> Bool
193
194 []      `lengthExceeds` n =  0 > n
195 (x:xs)  `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
196
197 isSingleton :: [a] -> Bool
198
199 isSingleton [x] = True
200 isSingleton  _  = False
201 \end{code}
202
203 \begin{code}
204 snocView :: [a] -> ([a], a)     -- Split off the last element
205 snocView xs = go xs []
206             where
207               go [x]    acc = (reverse acc, x)
208               go (x:xs) acc = go xs (x:acc)
209 \end{code}
210
211 Debugging/specialising versions of \tr{elem} and \tr{notElem}
212
213 \begin{code}
214 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
215
216 # ifndef DEBUG
217 isIn    msg x ys = elem__    x ys
218 isn'tIn msg x ys = notElem__ x ys
219
220 --these are here to be SPECIALIZEd (automagically)
221 elem__ _ []     = False
222 elem__ x (y:ys) = x==y || elem__ x ys
223
224 notElem__ x []     =  True
225 notElem__ x (y:ys) =  x /= y && notElem__ x ys
226
227 # else {- DEBUG -}
228 isIn msg x ys
229   = elem ILIT(0) x ys
230   where
231     elem i _ []     = False
232     elem i x (y:ys)
233       | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
234       | otherwise        = x == y || elem (i _ADD_ ILIT(1)) x ys
235
236 isn'tIn msg x ys
237   = notElem ILIT(0) x ys
238   where
239     notElem i x [] =  True
240     notElem i x (y:ys)
241       | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
242       | otherwise        =  x /= y && notElem (i _ADD_ ILIT(1)) x ys
243
244 # endif {- DEBUG -}
245
246 \end{code}
247
248 %************************************************************************
249 %*                                                                      *
250 \subsection[Utils-assoc]{Association lists}
251 %*                                                                      *
252 %************************************************************************
253
254 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
255
256 \begin{code}
257 assoc             :: (Eq a) => String -> [(a, b)] -> a -> b
258 assocDefault      :: (Eq a) => b -> [(a, b)] -> a -> b
259 assocUsing        :: (a -> a -> Bool) -> String -> [(a, b)] -> a -> b
260 assocDefaultUsing :: (a -> a -> Bool) -> b -> [(a, b)] -> a -> b
261
262 assocDefaultUsing eq deflt ((k,v) : rest) key
263   | k `eq` key = v
264   | otherwise  = assocDefaultUsing eq deflt rest key
265
266 assocDefaultUsing eq deflt [] key = deflt
267
268 assoc crash_msg         list key = assocDefaultUsing (==) (panic ("Failed in assoc: " ++ crash_msg)) list key
269 assocDefault deflt      list key = assocDefaultUsing (==) deflt list key
270 assocUsing eq crash_msg list key = assocDefaultUsing eq (panic ("Failed in assoc: " ++ crash_msg)) list key
271 \end{code}
272
273 %************************************************************************
274 %*                                                                      *
275 \subsection[Utils-dups]{Duplicate-handling}
276 %*                                                                      *
277 %************************************************************************
278
279 \begin{code}
280 hasNoDups :: (Eq a) => [a] -> Bool
281
282 hasNoDups xs = f [] xs
283   where
284     f seen_so_far []     = True
285     f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
286                                 False
287                            else
288                                 f (x:seen_so_far) xs
289
290     is_elem = isIn "hasNoDups"
291 \end{code}
292
293 \begin{code}
294 equivClasses :: (a -> a -> Ordering)    -- Comparison
295              -> [a]
296              -> [[a]]
297
298 equivClasses cmp stuff@[]     = []
299 equivClasses cmp stuff@[item] = [stuff]
300 equivClasses cmp items
301   = runs eq (sortLt lt items)
302   where
303     eq a b = case cmp a b of { EQ -> True; _ -> False }
304     lt a b = case cmp a b of { LT -> True; _ -> False }
305 \end{code}
306
307 The first cases in @equivClasses@ above are just to cut to the point
308 more quickly...
309
310 @runs@ groups a list into a list of lists, each sublist being a run of
311 identical elements of the input list. It is passed a predicate @p@ which
312 tells when two elements are equal.
313
314 \begin{code}
315 runs :: (a -> a -> Bool)        -- Equality
316      -> [a]
317      -> [[a]]
318
319 runs p []     = []
320 runs p (x:xs) = case (span (p x) xs) of
321                   (first, rest) -> (x:first) : (runs p rest)
322 \end{code}
323
324 \begin{code}
325 removeDups :: (a -> a -> Ordering)      -- Comparison function
326            -> [a]
327            -> ([a],     -- List with no duplicates
328                [[a]])   -- List of duplicate groups.  One representative from
329                         -- each group appears in the first result
330
331 removeDups cmp []  = ([], [])
332 removeDups cmp [x] = ([x],[])
333 removeDups cmp xs
334   = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
335     (xs', dups) }
336   where
337     collect_dups dups_so_far [x]         = (dups_so_far,      x)
338     collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
339 \end{code}
340
341
342 \begin{code}
343 equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]]
344         -- NB: it's *very* important that if we have the input list [a,b,c],
345         -- where a,b,c all have the same unique, then we get back the list
346         --      [a,b,c]
347         -- not
348         --      [c,b,a]
349         -- Hence the use of foldr, plus the reversed-args tack_on below
350 equivClassesByUniq get_uniq xs
351   = eltsUFM (foldr add emptyUFM xs)
352   where
353     add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a]
354     tack_on old new = new++old
355 \end{code}
356
357 %************************************************************************
358 %*                                                                      *
359 \subsection[Utils-sorting]{Sorting}
360 %*                                                                      *
361 %************************************************************************
362
363 %************************************************************************
364 %*                                                                      *
365 \subsubsection[Utils-quicksorting]{Quicksorts}
366 %*                                                                      *
367 %************************************************************************
368
369 \begin{code}
370 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
371 quicksort :: (a -> a -> Bool)           -- Less-than predicate
372           -> [a]                        -- Input list
373           -> [a]                        -- Result list in increasing order
374
375 quicksort lt []      = []
376 quicksort lt [x]     = [x]
377 quicksort lt (x:xs)  = split x [] [] xs
378   where
379     split x lo hi []                 = quicksort lt lo ++ (x : quicksort lt hi)
380     split x lo hi (y:ys) | y `lt` x  = split x (y:lo) hi ys
381                          | True      = split x lo (y:hi) ys
382 \end{code}
383
384 Quicksort variant from Lennart's Haskell-library contribution.  This
385 is a {\em stable} sort.
386
387 \begin{code}
388 stableSortLt = sortLt   -- synonym; when we want to highlight stable-ness
389
390 sortLt :: (a -> a -> Bool)              -- Less-than predicate
391        -> [a]                           -- Input list
392        -> [a]                           -- Result list
393
394 sortLt lt l = qsort lt   l []
395
396 -- qsort is stable and does not concatenate.
397 qsort :: (a -> a -> Bool)       -- Less-than predicate
398       -> [a]                    -- xs, Input list
399       -> [a]                    -- r,  Concatenate this list to the sorted input list
400       -> [a]                    -- Result = sort xs ++ r
401
402 qsort lt []     r = r
403 qsort lt [x]    r = x:r
404 qsort lt (x:xs) r = qpart lt x xs [] [] r
405
406 -- qpart partitions and sorts the sublists
407 -- rlt contains things less than x,
408 -- rge contains the ones greater than or equal to x.
409 -- Both have equal elements reversed with respect to the original list.
410
411 qpart lt x [] rlt rge r =
412     -- rlt and rge are in reverse order and must be sorted with an
413     -- anti-stable sorting
414     rqsort lt rlt (x : rqsort lt rge r)
415
416 qpart lt x (y:ys) rlt rge r =
417     if lt y x then
418         -- y < x
419         qpart lt x ys (y:rlt) rge r
420     else
421         -- y >= x
422         qpart lt x ys rlt (y:rge) r
423
424 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
425 rqsort lt []     r = r
426 rqsort lt [x]    r = x:r
427 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
428
429 rqpart lt x [] rle rgt r =
430     qsort lt rle (x : qsort lt rgt r)
431
432 rqpart lt x (y:ys) rle rgt r =
433     if lt x y then
434         -- y > x
435         rqpart lt x ys rle (y:rgt) r
436     else
437         -- y <= x
438         rqpart lt x ys (y:rle) rgt r
439 \end{code}
440
441 %************************************************************************
442 %*                                                                      *
443 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
444 %*                                                                      *
445 %************************************************************************
446
447 \begin{code}
448 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
449
450 mergesort cmp xs = merge_lists (split_into_runs [] xs)
451   where
452     a `le` b = case cmp a b of { LT -> True;  EQ -> True; GT -> False }
453     a `ge` b = case cmp a b of { LT -> False; EQ -> True; GT -> True  }
454
455     split_into_runs []        []                = []
456     split_into_runs run       []                = [run]
457     split_into_runs []        (x:xs)            = split_into_runs [x] xs
458     split_into_runs [r]       (x:xs) | x `ge` r = split_into_runs [r,x] xs
459     split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
460                                      | True     = rl : (split_into_runs [x] xs)
461
462     merge_lists []       = []
463     merge_lists (x:xs)   = merge x (merge_lists xs)
464
465     merge [] ys = ys
466     merge xs [] = xs
467     merge xl@(x:xs) yl@(y:ys)
468       = case cmp x y of
469           EQ  -> x : y : (merge xs ys)
470           LT  -> x : (merge xs yl)
471           GT -> y : (merge xl ys)
472 \end{code}
473
474 %************************************************************************
475 %*                                                                      *
476 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
477 %*                                                                      *
478 %************************************************************************
479
480 \begin{display}
481 Date: Mon, 3 May 93 20:45:23 +0200
482 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
483 To: partain@dcs.gla.ac.uk
484 Subject: natural merge sort beats quick sort [ and it is prettier ]
485
486 Here is a piece of Haskell code that I'm rather fond of. See it as an
487 attempt to get rid of the ridiculous quick-sort routine. group is
488 quite useful by itself I think it was John's idea originally though I
489 believe the lazy version is due to me [surprisingly complicated].
490 gamma [used to be called] is called gamma because I got inspired by
491 the Gamma calculus. It is not very close to the calculus but does
492 behave less sequentially than both foldr and foldl. One could imagine
493 a version of gamma that took a unit element as well thereby avoiding
494 the problem with empty lists.
495
496 I've tried this code against
497
498    1) insertion sort - as provided by haskell
499    2) the normal implementation of quick sort
500    3) a deforested version of quick sort due to Jan Sparud
501    4) a super-optimized-quick-sort of Lennart's
502
503 If the list is partially sorted both merge sort and in particular
504 natural merge sort wins. If the list is random [ average length of
505 rising subsequences = approx 2 ] mergesort still wins and natural
506 merge sort is marginally beaten by Lennart's soqs. The space
507 consumption of merge sort is a bit worse than Lennart's quick sort
508 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
509 fpca article ] isn't used because of group.
510
511 have fun
512 Carsten
513 \end{display}
514
515 \begin{code}
516 group :: (a -> a -> Bool) -> [a] -> [[a]]
517
518 {-
519 Date: Mon, 12 Feb 1996 15:09:41 +0000
520 From: Andy Gill <andy@dcs.gla.ac.uk>
521
522 Here is a `better' definition of group.
523 -}
524 group p []     = []
525 group p (x:xs) = group' xs x x (x :)
526   where
527     group' []     _     _     s  = [s []]
528     group' (x:xs) x_min x_max s 
529         | not (x `p` x_max) = group' xs x_min x (s . (x :)) 
530         | x `p` x_min       = group' xs x x_max ((x :) . s) 
531         | otherwise         = s [] : group' xs x x (x :) 
532
533 -- This one works forwards *and* backwards, as well as also being
534 -- faster that the one in Util.lhs.
535
536 {- ORIG:
537 group p [] = [[]]
538 group p (x:xs) =
539    let ((h1:t1):tt1) = group p xs
540        (t,tt) = if null xs then ([],[]) else
541                 if x `p` h1 then (h1:t1,tt1) else
542                    ([], (h1:t1):tt1)
543    in ((x:t):tt)
544 -}
545
546 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
547 generalMerge p xs [] = xs
548 generalMerge p [] ys = ys
549 generalMerge p (x:xs) (y:ys) | x `p` y   = x : generalMerge p xs (y:ys)
550                              | otherwise = y : generalMerge p (x:xs) ys
551
552 -- gamma is now called balancedFold
553
554 balancedFold :: (a -> a -> a) -> [a] -> a
555 balancedFold f [] = error "can't reduce an empty list using balancedFold"
556 balancedFold f [x] = x
557 balancedFold f l  = balancedFold f (balancedFold' f l)
558
559 balancedFold' :: (a -> a -> a) -> [a] -> [a]
560 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
561 balancedFold' f xs = xs
562
563 generalMergeSort p [] = []
564 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
565
566 generalNaturalMergeSort p [] = []
567 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
568
569 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
570
571 mergeSort = generalMergeSort (<=)
572 naturalMergeSort = generalNaturalMergeSort (<=)
573
574 mergeSortLe le = generalMergeSort le
575 naturalMergeSortLe le = generalNaturalMergeSort le
576 \end{code}
577
578 %************************************************************************
579 %*                                                                      *
580 \subsection[Utils-transitive-closure]{Transitive closure}
581 %*                                                                      *
582 %************************************************************************
583
584 This algorithm for transitive closure is straightforward, albeit quadratic.
585
586 \begin{code}
587 transitiveClosure :: (a -> [a])         -- Successor function
588                   -> (a -> a -> Bool)   -- Equality predicate
589                   -> [a]
590                   -> [a]                -- The transitive closure
591
592 transitiveClosure succ eq xs
593  = go [] xs
594  where
595    go done []                      = done
596    go done (x:xs) | x `is_in` done = go done xs
597                   | otherwise      = go (x:done) (succ x ++ xs)
598
599    x `is_in` []                 = False
600    x `is_in` (y:ys) | eq x y    = True
601                     | otherwise = x `is_in` ys
602 \end{code}
603
604 %************************************************************************
605 %*                                                                      *
606 \subsection[Utils-accum]{Accumulating}
607 %*                                                                      *
608 %************************************************************************
609
610 @mapAccumL@ behaves like a combination
611 of  @map@ and @foldl@;
612 it applies a function to each element of a list, passing an accumulating
613 parameter from left to right, and returning a final value of this
614 accumulator together with the new list.
615
616 \begin{code}
617 mapAccumL :: (acc -> x -> (acc, y))     -- Function of elt of input list
618                                         -- and accumulator, returning new
619                                         -- accumulator and elt of result list
620             -> acc              -- Initial accumulator
621             -> [x]              -- Input list
622             -> (acc, [y])               -- Final accumulator and result list
623
624 mapAccumL f b []     = (b, [])
625 mapAccumL f b (x:xs) = (b'', x':xs') where
626                                           (b', x') = f b x
627                                           (b'', xs') = mapAccumL f b' xs
628 \end{code}
629
630 @mapAccumR@ does the same, but working from right to left instead.  Its type is
631 the same as @mapAccumL@, though.
632
633 \begin{code}
634 mapAccumR :: (acc -> x -> (acc, y))     -- Function of elt of input list
635                                         -- and accumulator, returning new
636                                         -- accumulator and elt of result list
637             -> acc              -- Initial accumulator
638             -> [x]              -- Input list
639             -> (acc, [y])               -- Final accumulator and result list
640
641 mapAccumR f b []     = (b, [])
642 mapAccumR f b (x:xs) = (b'', x':xs') where
643                                           (b'', x') = f b' x
644                                           (b', xs') = mapAccumR f b xs
645 \end{code}
646
647 Here is the bi-directional version, that works from both left and right.
648
649 \begin{code}
650 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
651                                 -- Function of elt of input list
652                                 -- and accumulator, returning new
653                                 -- accumulator and elt of result list
654           -> accl                       -- Initial accumulator from left
655           -> accr                       -- Initial accumulator from right
656           -> [x]                        -- Input list
657           -> (accl, accr, [y])  -- Final accumulators and result list
658
659 mapAccumB f a b []     = (a,b,[])
660 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
661    where
662         (a',b'',y)  = f a b' x
663         (a'',b',ys) = mapAccumB f a' b xs
664 \end{code}
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection[Utils-comparison]{Comparisons}
669 %*                                                                      *
670 %************************************************************************
671
672 \begin{code}
673 thenCmp :: Ordering -> Ordering -> Ordering
674 {-# INLINE thenCmp #-}
675 thenCmp EQ   any = any
676 thenCmp other any = other
677
678 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
679     -- `cmpList' uses a user-specified comparer
680
681 cmpList cmp []     [] = EQ
682 cmpList cmp []     _  = LT
683 cmpList cmp _      [] = GT
684 cmpList cmp (a:as) (b:bs)
685   = case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
686 \end{code}
687
688 \begin{code}
689 cmpString :: String -> String -> Ordering
690
691 cmpString []     []     = EQ
692 cmpString (x:xs) (y:ys) = if      x == y then cmpString xs ys
693                           else if x  < y then LT
694                           else                GT
695 cmpString []     ys     = LT
696 cmpString xs     []     = GT
697
698 cmpString _ _ = panic "cmpString"
699 \end{code}
700
701
702 y
703 %************************************************************************
704 %*                                                                      *
705 \subsection[Utils-pairs]{Pairs}
706 %*                                                                      *
707 %************************************************************************
708
709 The following are curried versions of @fst@ and @snd@.
710
711 \begin{code}
712 cfst :: a -> b -> a     -- stranal-sem only (Note)
713 cfst x y = x
714 \end{code}
715
716 The following provide us higher order functions that, when applied
717 to a function, operate on pairs.
718
719 \begin{code}
720 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
721 applyToPair (f,g) (x,y) = (f x, g y)
722
723 applyToFst :: (a -> c) -> (a,b)-> (c,b)
724 applyToFst f (x,y) = (f x,y)
725
726 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
727 applyToSnd f (x,y) = (x,f y)
728
729 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
730 foldPair fg ab [] = ab
731 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
732                        where (u,v) = foldPair fg ab abs
733 \end{code}
734
735 \begin{code}
736 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
737 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
738 \end{code}
739
740