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