[project @ 1996-05-16 09:42:08 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,
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 #ifdef USE_FAST_STRINGS
71         cmpPString,
72 #else
73         substr,
74 #endif
75         -- pairs
76         IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
77         IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
78         unzipWith
79
80         -- error handling
81 #if defined(COMPILING_GHC)
82         , panic, panic#, pprPanic, pprPanic#, pprError, pprTrace
83         , assertPanic
84 #endif {- COMPILING_GHC -}
85
86         -- and to make the interface self-sufficient...
87 #if __HASKELL1__ < 3
88 # if defined(COMPILING_GHC)
89         , Maybe(..){-.. for pragmas...-}, PrettyRep, Pretty(..)
90 # else
91         , Maybe
92 # endif
93 #endif
94
95     ) where
96
97 #if defined(COMPILING_GHC)
98
99 CHK_Ubiq() -- debugging consistency check
100
101 import Pretty
102 #endif
103 #if __HASKELL1__ < 3
104 import Maybes           ( Maybe(..) )
105 #endif
106
107 infixr 9 `thenCmp`
108 \end{code}
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
113 %*                                                                      *
114 %************************************************************************
115
116 This is our own idea:
117 \begin{code}
118 #ifndef __GLASGOW_HASKELL__
119 data TAG_ = LT_ | EQ_ | GT_
120
121 tagCmp_ :: Ord a => a -> a -> TAG_
122 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
123 #endif
124 \end{code}
125
126 %************************************************************************
127 %*                                                                      *
128 \subsection[Utils-lists]{General list processing}
129 %*                                                                      *
130 %************************************************************************
131
132 Quantifiers are not standard in Haskell. The following fill in the gap.
133
134 \begin{code}
135 forall :: (a -> Bool) -> [a] -> Bool
136 forall pred []     = True
137 forall pred (x:xs) = pred x && forall pred xs
138
139 exists :: (a -> Bool) -> [a] -> Bool
140 exists pred []     = False
141 exists pred (x:xs) = pred x || exists pred xs
142 \end{code}
143
144 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
145 are of equal length.  Alastair Reid thinks this should only happen if
146 DEBUGging on; hey, why not?
147
148 \begin{code}
149 zipEqual        :: String -> [a] -> [b] -> [(a,b)]
150 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
151 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
152 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
153
154 #ifndef DEBUG
155 zipEqual      _ = zip
156 zipWithEqual  _ = zipWith
157 zipWith3Equal _ = zipWith3
158 zipWith4Equal _ = zipWith4
159 #else
160 zipEqual msg []     []     = []
161 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
162 zipEqual msg as     bs     = panic ("zipEqual: unequal lists:"++msg)
163
164 zipWithEqual msg z (a:as) (b:bs)=  z a b : zipWithEqual msg z as bs
165 zipWithEqual msg _ [] []        =  []
166 zipWithEqual msg _ _ _          =  panic ("zipWithEqual: unequal lists:"++msg)
167
168 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
169                                 =  z a b c : zipWith3Equal msg z as bs cs
170 zipWith3Equal msg _ [] []  []   =  []
171 zipWith3Equal msg _ _  _   _    =  panic ("zipWith3Equal: unequal lists:"++msg)
172
173 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
174                                 =  z a b c d : zipWith4Equal msg z as bs cs ds
175 zipWith4Equal msg _ [] [] [] [] =  []
176 zipWith4Equal msg _ _  _  _  _  =  panic ("zipWith4Equal: unequal lists:"++msg)
177 #endif
178 \end{code}
179
180 \begin{code}
181 -- zipLazy is lazy in the second list (observe the ~)
182
183 zipLazy :: [a] -> [b] -> [(a,b)]
184 zipLazy [] ys = []
185 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
186 \end{code}
187
188 \begin{code}
189 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
190
191 mapAndUnzip f [] = ([],[])
192 mapAndUnzip f (x:xs)
193   = let
194         (r1,  r2)  = f x
195         (rs1, rs2) = mapAndUnzip f xs
196     in
197     (r1:rs1, r2:rs2)
198 \end{code}
199
200 \begin{code}
201 nOfThem :: Int -> a -> [a]
202 nOfThem n thing = take n (repeat thing)
203
204 lengthExceeds :: [a] -> Int -> Bool
205
206 []      `lengthExceeds` n =  0 > n
207 (x:xs)  `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
208
209 isSingleton :: [a] -> Bool
210
211 isSingleton [x] = True
212 isSingleton  _  = False
213
214 startsWith, endsWith :: String -> String -> Maybe String
215
216 startsWith []     str = Just str
217 startsWith (c:cs) (s:ss)
218   = if c /= s then Nothing else startsWith cs ss
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 -> TAG_)        -- 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 -> TAG_)  -- 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 -> TAG_) -> [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  = do [] xs
591  where
592    do done []                      = done
593    do done (x:xs) | x `is_in` done = do done xs
594                   | otherwise      = do (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 class Ord3 a where
675   cmp :: a -> a -> TAG_
676
677 thenCmp :: TAG_ -> TAG_ -> TAG_
678 {-# INLINE thenCmp #-}
679 thenCmp EQ_   any = any
680 thenCmp other any = other
681
682 cmpList :: (a -> a -> TAG_) -> [a] -> [a] -> TAG_
683     -- `cmpList' uses a user-specified comparer
684
685 cmpList cmp []     [] = EQ_
686 cmpList cmp []     _  = LT_
687 cmpList cmp _      [] = GT_
688 cmpList cmp (a:as) (b:bs)
689   = case cmp a b of { EQ_ -> cmpList cmp as bs; xxx -> xxx }
690 \end{code}
691
692 \begin{code}
693 instance Ord3 a => Ord3 [a] where
694   cmp []     []     = EQ_
695   cmp (x:xs) []     = GT_
696   cmp []     (y:ys) = LT_
697   cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
698
699 instance Ord3 a => Ord3 (Maybe a) where
700   cmp Nothing  Nothing  = EQ_
701   cmp Nothing  (Just y) = LT_
702   cmp (Just x) Nothing  = GT_
703   cmp (Just x) (Just y) = x `cmp` y
704
705 instance Ord3 Int where
706   cmp a b | a < b     = LT_
707           | a > b     = GT_
708           | otherwise = EQ_
709 \end{code}
710
711 \begin{code}
712 cmpString :: String -> String -> TAG_
713
714 cmpString []     []     = EQ_
715 cmpString (x:xs) (y:ys) = if      x == y then cmpString xs ys
716                           else if x  < y then LT_
717                           else                GT_
718 cmpString []     ys     = LT_
719 cmpString xs     []     = GT_
720
721 cmpString _ _ = panic# "cmpString"
722 \end{code}
723
724 \begin{code}
725 #ifdef USE_FAST_STRINGS
726 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
727
728 cmpPString x y
729   = case (_tagCmp x y) of { _LT -> LT_ ; _EQ -> EQ_ ; _GT -> GT_ }
730 #endif
731 \end{code}
732
733 \begin{code}
734 #ifndef USE_FAST_STRINGS
735 substr :: FAST_STRING -> Int -> Int -> FAST_STRING
736
737 substr str beg end
738   = ASSERT (beg >= 0 && beg <= end)
739     take (end - beg + 1) (drop beg str)
740 #endif
741 \end{code}
742
743 %************************************************************************
744 %*                                                                      *
745 \subsection[Utils-pairs]{Pairs}
746 %*                                                                      *
747 %************************************************************************
748
749 The following are curried versions of @fst@ and @snd@.
750
751 \begin{code}
752 cfst :: a -> b -> a     -- stranal-sem only (Note)
753 cfst x y = x
754 \end{code}
755
756 The following provide us higher order functions that, when applied
757 to a function, operate on pairs.
758
759 \begin{code}
760 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
761 applyToPair (f,g) (x,y) = (f x, g y)
762
763 applyToFst :: (a -> c) -> (a,b)-> (c,b)
764 applyToFst f (x,y) = (f x,y)
765
766 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
767 applyToSnd f (x,y) = (x,f y)
768
769 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
770 foldPair fg ab [] = ab
771 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
772                        where (u,v) = foldPair fg ab abs
773 \end{code}
774
775 \begin{code}
776 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
777 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
778 \end{code}
779
780 %************************************************************************
781 %*                                                                      *
782 \subsection[Utils-errors]{Error handling}
783 %*                                                                      *
784 %************************************************************************
785
786 \begin{code}
787 #if defined(COMPILING_GHC)
788 panic x = error ("panic! (the `impossible' happened):\n\t"
789               ++ x ++ "\n\n"
790               ++ "Please report it as a compiler bug "
791               ++ "to glasgow-haskell-bugs@dcs.glasgow.ac.uk.\n\n" )
792
793 pprPanic heading pretty_msg = panic (heading++(ppShow 80 pretty_msg))
794 pprError heading pretty_msg = error (heading++(ppShow 80 pretty_msg))
795 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
796
797 -- #-versions because panic can't return an unboxed int, and that's
798 -- what TAG_ is with GHC at the moment.  Ugh. (Simon)
799 -- No, man -- Too Beautiful! (Will)
800
801 panic# :: String -> TAG_
802 panic# s = case (panic s) of () -> EQ_
803
804 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
805
806 assertPanic :: String -> Int -> a
807 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
808
809 #endif {- COMPILING_GHC -}
810 \end{code}