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