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