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