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