[project @ 2000-10-12 13:11:45 by simonmar]
[ghc-hetmet.git] / ghc / compiler / utils / Util.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Util]{Highly random utility functions}
5
6 \begin{code}
7 -- IF_NOT_GHC is meant to make this module useful outside the context of GHC
8 #define IF_NOT_GHC(a)
9
10 module Util (
11 #if NOT_USED
12         -- The Eager monad
13         Eager, thenEager, returnEager, mapEager, appEager, runEager,
14 #endif
15
16         -- general list processing
17         zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
18         zipLazy, stretchZipWith,
19         mapAndUnzip, mapAndUnzip3,
20         nOfThem, lengthExceeds, isSingleton, only,
21         snocView,
22         isIn, isn'tIn,
23
24         -- for-loop
25         nTimes,
26
27         -- sorting
28         IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
29         sortLt,
30         IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
31         IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
32
33         -- transitive closures
34         transitiveClosure,
35
36         -- accumulating
37         mapAccumL, mapAccumR, mapAccumB, foldl2, count,
38
39         -- comparisons
40         thenCmp, cmpList, prefixMatch, postfixMatch,
41
42         -- strictness
43         seqList, ($!),
44
45         -- pairs
46         IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
47         IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
48         unzipWith
49
50         -- I/O
51 #if __GLASGOW_HASKELL__ < 402
52         , bracket
53 #endif
54
55         , global
56
57     ) where
58
59 #include "HsVersions.h"
60
61 import List             ( zipWith4 )
62 import Panic            ( panic )
63 import IOExts           ( IORef, newIORef, unsafePerformIO )
64 import FastTypes
65
66 infixr 9 `thenCmp`
67 \end{code}
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection{The Eager monad}
72 %*                                                                      *
73 %************************************************************************
74
75 The @Eager@ monad is just an encoding of continuation-passing style,
76 used to allow you to express "do this and then that", mainly to avoid
77 space leaks. It's done with a type synonym to save bureaucracy.
78
79 \begin{code}
80 #if NOT_USED
81
82 type Eager ans a = (a -> ans) -> ans
83
84 runEager :: Eager a a -> a
85 runEager m = m (\x -> x)
86
87 appEager :: Eager ans a -> (a -> ans) -> ans
88 appEager m cont = m cont
89
90 thenEager :: Eager ans a -> (a -> Eager ans b) -> Eager ans b
91 thenEager m k cont = m (\r -> k r cont)
92
93 returnEager :: a -> Eager ans a
94 returnEager v cont = cont v
95
96 mapEager :: (a -> Eager ans b) -> [a] -> Eager ans [b]
97 mapEager f [] = returnEager []
98 mapEager f (x:xs) = f x                 `thenEager` \ y ->
99                     mapEager f xs       `thenEager` \ ys ->
100                     returnEager (y:ys)
101 #endif
102 \end{code}
103
104 %************************************************************************
105 %*                                                                      *
106 \subsection{A for loop}
107 %*                                                                      *
108 %************************************************************************
109
110 \begin{code}
111 -- Compose a function with itself n times.  (nth rather than twice)
112 nTimes :: Int -> (a -> a) -> (a -> a)
113 nTimes 0 _ = id
114 nTimes 1 f = f
115 nTimes n f = f . nTimes (n-1) f
116 \end{code}
117
118
119 %************************************************************************
120 %*                                                                      *
121 \subsection[Utils-lists]{General list processing}
122 %*                                                                      *
123 %************************************************************************
124
125 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
126 are of equal length.  Alastair Reid thinks this should only happen if
127 DEBUGging on; hey, why not?
128
129 \begin{code}
130 zipEqual        :: String -> [a] -> [b] -> [(a,b)]
131 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
132 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
133 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
134
135 #ifndef DEBUG
136 zipEqual      _ = zip
137 zipWithEqual  _ = zipWith
138 zipWith3Equal _ = zipWith3
139 zipWith4Equal _ = zipWith4
140 #else
141 zipEqual msg []     []     = []
142 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
143 zipEqual msg as     bs     = panic ("zipEqual: unequal lists:"++msg)
144
145 zipWithEqual msg z (a:as) (b:bs)=  z a b : zipWithEqual msg z as bs
146 zipWithEqual msg _ [] []        =  []
147 zipWithEqual msg _ _ _          =  panic ("zipWithEqual: unequal lists:"++msg)
148
149 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
150                                 =  z a b c : zipWith3Equal msg z as bs cs
151 zipWith3Equal msg _ [] []  []   =  []
152 zipWith3Equal msg _ _  _   _    =  panic ("zipWith3Equal: unequal lists:"++msg)
153
154 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
155                                 =  z a b c d : zipWith4Equal msg z as bs cs ds
156 zipWith4Equal msg _ [] [] [] [] =  []
157 zipWith4Equal msg _ _  _  _  _  =  panic ("zipWith4Equal: unequal lists:"++msg)
158 #endif
159 \end{code}
160
161 \begin{code}
162 -- zipLazy is lazy in the second list (observe the ~)
163
164 zipLazy :: [a] -> [b] -> [(a,b)]
165 zipLazy [] ys = []
166 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
167 \end{code}
168
169
170 \begin{code}
171 stretchZipWith :: (a -> Bool) -> b -> (a->b->c) -> [a] -> [b] -> [c]
172 -- (stretchZipWith p z f xs ys) stretches ys by inserting z in 
173 -- the places where p returns *True*
174
175 stretchZipWith p z f [] ys = []
176 stretchZipWith p z f (x:xs) ys
177   | p x       = f x z : stretchZipWith p z f xs ys
178   | otherwise = case ys of
179                   []     -> []
180                   (y:ys) -> f x y : stretchZipWith p z f xs ys
181 \end{code}
182
183
184 \begin{code}
185 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
186
187 mapAndUnzip f [] = ([],[])
188 mapAndUnzip f (x:xs)
189   = let
190         (r1,  r2)  = f x
191         (rs1, rs2) = mapAndUnzip f xs
192     in
193     (r1:rs1, r2:rs2)
194
195 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
196
197 mapAndUnzip3 f [] = ([],[],[])
198 mapAndUnzip3 f (x:xs)
199   = let
200         (r1,  r2,  r3)  = f x
201         (rs1, rs2, rs3) = mapAndUnzip3 f xs
202     in
203     (r1:rs1, r2:rs2, r3:rs3)
204 \end{code}
205
206 \begin{code}
207 nOfThem :: Int -> a -> [a]
208 nOfThem n thing = replicate n thing
209
210 lengthExceeds :: [a] -> Int -> Bool
211 -- (lengthExceeds xs n) is True if   length xs > n
212 (x:xs)  `lengthExceeds` n = n < 1 || xs `lengthExceeds` (n - 1)
213 []      `lengthExceeds` n = n < 0
214
215 isSingleton :: [a] -> Bool
216 isSingleton [x] = True
217 isSingleton  _  = False
218
219 only :: [a] -> a
220 #ifdef DEBUG
221 only [a] = a
222 #else
223 only (a:_) = a
224 #endif
225 \end{code}
226
227 \begin{code}
228 snocView :: [a] -> ([a], a)     -- Split off the last element
229 snocView xs = go xs []
230             where
231               go [x]    acc = (reverse acc, x)
232               go (x:xs) acc = go xs (x:acc)
233 \end{code}
234
235 Debugging/specialising versions of \tr{elem} and \tr{notElem}
236
237 \begin{code}
238 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
239
240 # ifndef DEBUG
241 isIn    msg x ys = elem__    x ys
242 isn'tIn msg x ys = notElem__ x ys
243
244 --these are here to be SPECIALIZEd (automagically)
245 elem__ _ []     = False
246 elem__ x (y:ys) = x==y || elem__ x ys
247
248 notElem__ x []     =  True
249 notElem__ x (y:ys) =  x /= y && notElem__ x ys
250
251 # else {- DEBUG -}
252 isIn msg x ys
253   = elem (_ILIT 0) x ys
254   where
255     elem i _ []     = False
256     elem i x (y:ys)
257       | i ># _ILIT 100 = panic ("Over-long elem in: " ++ msg)
258       | otherwise        = x == y || elem (i +# _ILIT(1)) x ys
259
260 isn'tIn msg x ys
261   = notElem (_ILIT 0) x ys
262   where
263     notElem i x [] =  True
264     notElem i x (y:ys)
265       | i ># _ILIT 100 = panic ("Over-long notElem in: " ++ msg)
266       | otherwise        =  x /= y && notElem (i +# _ILIT(1)) x ys
267
268 # endif {- DEBUG -}
269
270 \end{code}
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection[Utils-sorting]{Sorting}
275 %*                                                                      *
276 %************************************************************************
277
278 %************************************************************************
279 %*                                                                      *
280 \subsubsection[Utils-quicksorting]{Quicksorts}
281 %*                                                                      *
282 %************************************************************************
283
284 \begin{code}
285 #if NOT_USED
286
287 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
288 quicksort :: (a -> a -> Bool)           -- Less-than predicate
289           -> [a]                        -- Input list
290           -> [a]                        -- Result list in increasing order
291
292 quicksort lt []      = []
293 quicksort lt [x]     = [x]
294 quicksort lt (x:xs)  = split x [] [] xs
295   where
296     split x lo hi []                 = quicksort lt lo ++ (x : quicksort lt hi)
297     split x lo hi (y:ys) | y `lt` x  = split x (y:lo) hi ys
298                          | True      = split x lo (y:hi) ys
299 #endif
300 \end{code}
301
302 Quicksort variant from Lennart's Haskell-library contribution.  This
303 is a {\em stable} sort.
304
305 \begin{code}
306 stableSortLt = sortLt   -- synonym; when we want to highlight stable-ness
307
308 sortLt :: (a -> a -> Bool)              -- Less-than predicate
309        -> [a]                           -- Input list
310        -> [a]                           -- Result list
311
312 sortLt lt l = qsort lt   l []
313
314 -- qsort is stable and does not concatenate.
315 qsort :: (a -> a -> Bool)       -- Less-than predicate
316       -> [a]                    -- xs, Input list
317       -> [a]                    -- r,  Concatenate this list to the sorted input list
318       -> [a]                    -- Result = sort xs ++ r
319
320 qsort lt []     r = r
321 qsort lt [x]    r = x:r
322 qsort lt (x:xs) r = qpart lt x xs [] [] r
323
324 -- qpart partitions and sorts the sublists
325 -- rlt contains things less than x,
326 -- rge contains the ones greater than or equal to x.
327 -- Both have equal elements reversed with respect to the original list.
328
329 qpart lt x [] rlt rge r =
330     -- rlt and rge are in reverse order and must be sorted with an
331     -- anti-stable sorting
332     rqsort lt rlt (x : rqsort lt rge r)
333
334 qpart lt x (y:ys) rlt rge r =
335     if lt y x then
336         -- y < x
337         qpart lt x ys (y:rlt) rge r
338     else
339         -- y >= x
340         qpart lt x ys rlt (y:rge) r
341
342 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
343 rqsort lt []     r = r
344 rqsort lt [x]    r = x:r
345 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
346
347 rqpart lt x [] rle rgt r =
348     qsort lt rle (x : qsort lt rgt r)
349
350 rqpart lt x (y:ys) rle rgt r =
351     if lt x y then
352         -- y > x
353         rqpart lt x ys rle (y:rgt) r
354     else
355         -- y <= x
356         rqpart lt x ys (y:rle) rgt r
357 \end{code}
358
359 %************************************************************************
360 %*                                                                      *
361 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
362 %*                                                                      *
363 %************************************************************************
364
365 \begin{code}
366 #if NOT_USED
367 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
368
369 mergesort cmp xs = merge_lists (split_into_runs [] xs)
370   where
371     a `le` b = case cmp a b of { LT -> True;  EQ -> True; GT -> False }
372     a `ge` b = case cmp a b of { LT -> False; EQ -> True; GT -> True  }
373
374     split_into_runs []        []                = []
375     split_into_runs run       []                = [run]
376     split_into_runs []        (x:xs)            = split_into_runs [x] xs
377     split_into_runs [r]       (x:xs) | x `ge` r = split_into_runs [r,x] xs
378     split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
379                                      | True     = rl : (split_into_runs [x] xs)
380
381     merge_lists []       = []
382     merge_lists (x:xs)   = merge x (merge_lists xs)
383
384     merge [] ys = ys
385     merge xs [] = xs
386     merge xl@(x:xs) yl@(y:ys)
387       = case cmp x y of
388           EQ  -> x : y : (merge xs ys)
389           LT  -> x : (merge xs yl)
390           GT -> y : (merge xl ys)
391 #endif
392 \end{code}
393
394 %************************************************************************
395 %*                                                                      *
396 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
397 %*                                                                      *
398 %************************************************************************
399
400 \begin{display}
401 Date: Mon, 3 May 93 20:45:23 +0200
402 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
403 To: partain@dcs.gla.ac.uk
404 Subject: natural merge sort beats quick sort [ and it is prettier ]
405
406 Here is a piece of Haskell code that I'm rather fond of. See it as an
407 attempt to get rid of the ridiculous quick-sort routine. group is
408 quite useful by itself I think it was John's idea originally though I
409 believe the lazy version is due to me [surprisingly complicated].
410 gamma [used to be called] is called gamma because I got inspired by
411 the Gamma calculus. It is not very close to the calculus but does
412 behave less sequentially than both foldr and foldl. One could imagine
413 a version of gamma that took a unit element as well thereby avoiding
414 the problem with empty lists.
415
416 I've tried this code against
417
418    1) insertion sort - as provided by haskell
419    2) the normal implementation of quick sort
420    3) a deforested version of quick sort due to Jan Sparud
421    4) a super-optimized-quick-sort of Lennart's
422
423 If the list is partially sorted both merge sort and in particular
424 natural merge sort wins. If the list is random [ average length of
425 rising subsequences = approx 2 ] mergesort still wins and natural
426 merge sort is marginally beaten by Lennart's soqs. The space
427 consumption of merge sort is a bit worse than Lennart's quick sort
428 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
429 fpca article ] isn't used because of group.
430
431 have fun
432 Carsten
433 \end{display}
434
435 \begin{code}
436 group :: (a -> a -> Bool) -> [a] -> [[a]]
437
438 {-
439 Date: Mon, 12 Feb 1996 15:09:41 +0000
440 From: Andy Gill <andy@dcs.gla.ac.uk>
441
442 Here is a `better' definition of group.
443 -}
444 group p []     = []
445 group p (x:xs) = group' xs x x (x :)
446   where
447     group' []     _     _     s  = [s []]
448     group' (x:xs) x_min x_max s 
449         | not (x `p` x_max) = group' xs x_min x (s . (x :)) 
450         | x `p` x_min       = group' xs x x_max ((x :) . s) 
451         | otherwise         = s [] : group' xs x x (x :) 
452
453 -- This one works forwards *and* backwards, as well as also being
454 -- faster that the one in Util.lhs.
455
456 {- ORIG:
457 group p [] = [[]]
458 group p (x:xs) =
459    let ((h1:t1):tt1) = group p xs
460        (t,tt) = if null xs then ([],[]) else
461                 if x `p` h1 then (h1:t1,tt1) else
462                    ([], (h1:t1):tt1)
463    in ((x:t):tt)
464 -}
465
466 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
467 generalMerge p xs [] = xs
468 generalMerge p [] ys = ys
469 generalMerge p (x:xs) (y:ys) | x `p` y   = x : generalMerge p xs (y:ys)
470                              | otherwise = y : generalMerge p (x:xs) ys
471
472 -- gamma is now called balancedFold
473
474 balancedFold :: (a -> a -> a) -> [a] -> a
475 balancedFold f [] = error "can't reduce an empty list using balancedFold"
476 balancedFold f [x] = x
477 balancedFold f l  = balancedFold f (balancedFold' f l)
478
479 balancedFold' :: (a -> a -> a) -> [a] -> [a]
480 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
481 balancedFold' f xs = xs
482
483 generalMergeSort p [] = []
484 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
485
486 generalNaturalMergeSort p [] = []
487 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
488
489 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
490
491 mergeSort = generalMergeSort (<=)
492 naturalMergeSort = generalNaturalMergeSort (<=)
493
494 mergeSortLe le = generalMergeSort le
495 naturalMergeSortLe le = generalNaturalMergeSort le
496 \end{code}
497
498 %************************************************************************
499 %*                                                                      *
500 \subsection[Utils-transitive-closure]{Transitive closure}
501 %*                                                                      *
502 %************************************************************************
503
504 This algorithm for transitive closure is straightforward, albeit quadratic.
505
506 \begin{code}
507 transitiveClosure :: (a -> [a])         -- Successor function
508                   -> (a -> a -> Bool)   -- Equality predicate
509                   -> [a]
510                   -> [a]                -- The transitive closure
511
512 transitiveClosure succ eq xs
513  = go [] xs
514  where
515    go done []                      = done
516    go done (x:xs) | x `is_in` done = go done xs
517                   | otherwise      = go (x:done) (succ x ++ xs)
518
519    x `is_in` []                 = False
520    x `is_in` (y:ys) | eq x y    = True
521                     | otherwise = x `is_in` ys
522 \end{code}
523
524 %************************************************************************
525 %*                                                                      *
526 \subsection[Utils-accum]{Accumulating}
527 %*                                                                      *
528 %************************************************************************
529
530 @mapAccumL@ behaves like a combination
531 of  @map@ and @foldl@;
532 it applies a function to each element of a list, passing an accumulating
533 parameter from left to right, and returning a final value of this
534 accumulator together with the new list.
535
536 \begin{code}
537 mapAccumL :: (acc -> x -> (acc, y))     -- Function of elt of input list
538                                         -- and accumulator, returning new
539                                         -- accumulator and elt of result list
540             -> acc              -- Initial accumulator
541             -> [x]              -- Input list
542             -> (acc, [y])               -- Final accumulator and result list
543
544 mapAccumL f b []     = (b, [])
545 mapAccumL f b (x:xs) = (b'', x':xs') where
546                                           (b', x') = f b x
547                                           (b'', xs') = mapAccumL f b' xs
548 \end{code}
549
550 @mapAccumR@ does the same, but working from right to left instead.  Its type is
551 the same as @mapAccumL@, though.
552
553 \begin{code}
554 mapAccumR :: (acc -> x -> (acc, y))     -- Function of elt of input list
555                                         -- and accumulator, returning new
556                                         -- accumulator and elt of result list
557             -> acc              -- Initial accumulator
558             -> [x]              -- Input list
559             -> (acc, [y])               -- Final accumulator and result list
560
561 mapAccumR f b []     = (b, [])
562 mapAccumR f b (x:xs) = (b'', x':xs') where
563                                           (b'', x') = f b' x
564                                           (b', xs') = mapAccumR f b xs
565 \end{code}
566
567 Here is the bi-directional version, that works from both left and right.
568
569 \begin{code}
570 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
571                                 -- Function of elt of input list
572                                 -- and accumulator, returning new
573                                 -- accumulator and elt of result list
574           -> accl                       -- Initial accumulator from left
575           -> accr                       -- Initial accumulator from right
576           -> [x]                        -- Input list
577           -> (accl, accr, [y])  -- Final accumulators and result list
578
579 mapAccumB f a b []     = (a,b,[])
580 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
581    where
582         (a',b'',y)  = f a b' x
583         (a'',b',ys) = mapAccumB f a' b xs
584 \end{code}
585
586 A combination of foldl with zip.  It works with equal length lists.
587
588 \begin{code}
589 foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
590 foldl2 k z [] [] = z
591 foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
592 \end{code}
593
594 Count the number of times a predicate is true
595
596 \begin{code}
597 count :: (a -> Bool) -> [a] -> Int
598 count p [] = 0
599 count p (x:xs) | p x       = 1 + count p xs
600                | otherwise = count p xs
601 \end{code}
602
603
604 %************************************************************************
605 %*                                                                      *
606 \subsection[Utils-comparison]{Comparisons}
607 %*                                                                      *
608 %************************************************************************
609
610 \begin{code}
611 thenCmp :: Ordering -> Ordering -> Ordering
612 {-# INLINE thenCmp #-}
613 thenCmp EQ   any = any
614 thenCmp other any = other
615
616 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
617     -- `cmpList' uses a user-specified comparer
618
619 cmpList cmp []     [] = EQ
620 cmpList cmp []     _  = LT
621 cmpList cmp _      [] = GT
622 cmpList cmp (a:as) (b:bs)
623   = case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
624 \end{code}
625
626 \begin{code}
627 prefixMatch :: Eq a => [a] -> [a] -> Bool
628 prefixMatch [] _str = True
629 prefixMatch _pat [] = False
630 prefixMatch (p:ps) (s:ss) | p == s    = prefixMatch ps ss
631                           | otherwise = False
632
633 postfixMatch :: Eq a => [a] -> [a] -> Bool
634 postfixMatch pat str = prefixMatch (reverse pat) (reverse str)
635 \end{code}
636
637 %************************************************************************
638 %*                                                                      *
639 \subsection[Utils-pairs]{Pairs}
640 %*                                                                      *
641 %************************************************************************
642
643 The following are curried versions of @fst@ and @snd@.
644
645 \begin{code}
646 cfst :: a -> b -> a     -- stranal-sem only (Note)
647 cfst x y = x
648 \end{code}
649
650 The following provide us higher order functions that, when applied
651 to a function, operate on pairs.
652
653 \begin{code}
654 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
655 applyToPair (f,g) (x,y) = (f x, g y)
656
657 applyToFst :: (a -> c) -> (a,b)-> (c,b)
658 applyToFst f (x,y) = (f x,y)
659
660 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
661 applyToSnd f (x,y) = (x,f y)
662
663 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
664 foldPair fg ab [] = ab
665 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
666                        where (u,v) = foldPair fg ab abs
667 \end{code}
668
669 \begin{code}
670 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
671 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
672 \end{code}
673
674 \begin{code}
675 #if __HASKELL1__ > 4
676 seqList :: [a] -> b -> b
677 #else
678 seqList :: (Eval a) => [a] -> b -> b
679 #endif
680 seqList [] b = b
681 seqList (x:xs) b = x `seq` seqList xs b
682
683 #if __HASKELL1__ <= 4
684 ($!)    :: (Eval a) => (a -> b) -> a -> b
685 f $! x  = x `seq` f x
686 #endif
687 \end{code}
688
689 \begin{code}
690 #if __GLASGOW_HASKELL__ < 402
691 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
692 bracket before after thing = do
693   a <- before 
694   r <- (thing a) `catch` (\err -> after a >> fail err)
695   after a
696   return r
697 #endif
698 \end{code}
699
700 Global variables:
701
702 \begin{code}
703 global :: a -> IORef a
704 global a = unsafePerformIO (newIORef a)
705 \end{code}
706