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