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