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