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