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