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