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