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