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