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