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