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