2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Util]{Highly random utility functions}
7 -- IF_NOT_GHC is meant to make this module useful outside the context of GHC
13 Eager, thenEager, returnEager, mapEager, appEager, runEager,
16 -- general list processing
17 zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
18 zipLazy, stretchZipWith,
19 mapAndUnzip, mapAndUnzip3,
20 nOfThem, lengthExceeds, isSingleton, only,
28 IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
30 IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
31 IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
33 -- transitive closures
37 mapAccumL, mapAccumR, mapAccumB, foldl2, count,
40 thenCmp, cmpList, prefixMatch, postfixMatch,
46 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
47 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
51 #if __GLASGOW_HASKELL__ < 402
58 #if __GLASGOW_HASKELL__ <= 408
66 #include "HsVersions.h"
68 import IO ( hPutStrLn, stderr )
69 import List ( zipWith4 )
70 import Panic ( panic )
71 import IOExts ( IORef, newIORef, unsafePerformIO )
73 #if __GLASGOW_HASKELL__ <= 408
74 import Exception ( catchIO, justIoErrors, raiseInThread )
79 %************************************************************************
81 \subsection{The Eager monad}
83 %************************************************************************
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.
92 type Eager ans a = (a -> ans) -> ans
94 runEager :: Eager a a -> a
95 runEager m = m (\x -> x)
97 appEager :: Eager ans a -> (a -> ans) -> ans
98 appEager m cont = m cont
100 thenEager :: Eager ans a -> (a -> Eager ans b) -> Eager ans b
101 thenEager m k cont = m (\r -> k r cont)
103 returnEager :: a -> Eager ans a
104 returnEager v cont = cont v
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 ->
114 %************************************************************************
116 \subsection{A for loop}
118 %************************************************************************
121 -- Compose a function with itself n times. (nth rather than twice)
122 nTimes :: Int -> (a -> a) -> (a -> a)
125 nTimes n f = f . nTimes (n-1) f
129 %************************************************************************
131 \subsection[Utils-lists]{General list processing}
133 %************************************************************************
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?
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]
147 zipWithEqual _ = zipWith
148 zipWith3Equal _ = zipWith3
149 zipWith4Equal _ = zipWith4
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)
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)
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)
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)
172 -- zipLazy is lazy in the second list (observe the ~)
174 zipLazy :: [a] -> [b] -> [(a,b)]
176 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
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*
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
190 (y:ys) -> f x y : stretchZipWith p z f xs ys
195 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
197 mapAndUnzip f [] = ([],[])
201 (rs1, rs2) = mapAndUnzip f xs
205 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
207 mapAndUnzip3 f [] = ([],[],[])
208 mapAndUnzip3 f (x:xs)
211 (rs1, rs2, rs3) = mapAndUnzip3 f xs
213 (r1:rs1, r2:rs2, r3:rs3)
217 nOfThem :: Int -> a -> [a]
218 nOfThem n thing = replicate n thing
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
225 isSingleton :: [a] -> Bool
226 isSingleton [x] = True
227 isSingleton _ = False
238 snocView :: [a] -> ([a], a) -- Split off the last element
239 snocView xs = go xs []
241 go [x] acc = (reverse acc, x)
242 go (x:xs) acc = go xs (x:acc)
245 Debugging/specialising versions of \tr{elem} and \tr{notElem}
248 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
251 isIn msg x ys = elem__ x ys
252 isn'tIn msg x ys = notElem__ x ys
254 --these are here to be SPECIALIZEd (automagically)
256 elem__ x (y:ys) = x==y || elem__ x ys
258 notElem__ x [] = True
259 notElem__ x (y:ys) = x /= y && notElem__ x ys
263 = elem (_ILIT 0) x ys
267 | i ># _ILIT 100 = panic ("Over-long elem in: " ++ msg)
268 | otherwise = x == y || elem (i +# _ILIT(1)) x ys
271 = notElem (_ILIT 0) x ys
273 notElem i x [] = True
275 | i ># _ILIT 100 = panic ("Over-long notElem in: " ++ msg)
276 | otherwise = x /= y && notElem (i +# _ILIT(1)) x ys
282 %************************************************************************
284 \subsection[Utils-sorting]{Sorting}
286 %************************************************************************
288 %************************************************************************
290 \subsubsection[Utils-quicksorting]{Quicksorts}
292 %************************************************************************
297 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
298 quicksort :: (a -> a -> Bool) -- Less-than predicate
300 -> [a] -- Result list in increasing order
303 quicksort lt [x] = [x]
304 quicksort lt (x:xs) = split x [] [] xs
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
312 Quicksort variant from Lennart's Haskell-library contribution. This
313 is a {\em stable} sort.
316 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
318 sortLt :: (a -> a -> Bool) -- Less-than predicate
320 -> [a] -- Result list
322 sortLt lt l = qsort lt l []
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
332 qsort lt (x:xs) r = qpart lt x xs [] [] r
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.
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)
344 qpart lt x (y:ys) rlt rge r =
347 qpart lt x ys (y:rlt) rge r
350 qpart lt x ys rlt (y:rge) r
352 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
354 rqsort lt [x] r = x:r
355 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
357 rqpart lt x [] rle rgt r =
358 qsort lt rle (x : qsort lt rgt r)
360 rqpart lt x (y:ys) rle rgt r =
363 rqpart lt x ys rle (y:rgt) r
366 rqpart lt x ys (y:rle) rgt r
369 %************************************************************************
371 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
373 %************************************************************************
377 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
379 mergesort cmp xs = merge_lists (split_into_runs [] xs)
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 }
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)
392 merge_lists (x:xs) = merge x (merge_lists xs)
396 merge xl@(x:xs) yl@(y:ys)
398 EQ -> x : y : (merge xs ys)
399 LT -> x : (merge xs yl)
400 GT -> y : (merge xl ys)
404 %************************************************************************
406 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
408 %************************************************************************
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 ]
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.
426 I've tried this code against
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
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.
446 group :: (a -> a -> Bool) -> [a] -> [[a]]
449 Date: Mon, 12 Feb 1996 15:09:41 +0000
450 From: Andy Gill <andy@dcs.gla.ac.uk>
452 Here is a `better' definition of group.
455 group p (x:xs) = group' xs x x (x :)
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 :)
463 -- This one works forwards *and* backwards, as well as also being
464 -- faster that the one in Util.lhs.
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
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
482 -- gamma is now called balancedFold
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)
489 balancedFold' :: (a -> a -> a) -> [a] -> [a]
490 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
491 balancedFold' f xs = xs
493 generalMergeSort p [] = []
494 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
496 generalNaturalMergeSort p [] = []
497 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
499 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
501 mergeSort = generalMergeSort (<=)
502 naturalMergeSort = generalNaturalMergeSort (<=)
504 mergeSortLe le = generalMergeSort le
505 naturalMergeSortLe le = generalNaturalMergeSort le
508 %************************************************************************
510 \subsection[Utils-transitive-closure]{Transitive closure}
512 %************************************************************************
514 This algorithm for transitive closure is straightforward, albeit quadratic.
517 transitiveClosure :: (a -> [a]) -- Successor function
518 -> (a -> a -> Bool) -- Equality predicate
520 -> [a] -- The transitive closure
522 transitiveClosure succ eq xs
526 go done (x:xs) | x `is_in` done = go done xs
527 | otherwise = go (x:done) (succ x ++ xs)
530 x `is_in` (y:ys) | eq x y = True
531 | otherwise = x `is_in` ys
534 %************************************************************************
536 \subsection[Utils-accum]{Accumulating}
538 %************************************************************************
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.
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
552 -> (acc, [y]) -- Final accumulator and result list
554 mapAccumL f b [] = (b, [])
555 mapAccumL f b (x:xs) = (b'', x':xs') where
557 (b'', xs') = mapAccumL f b' xs
560 @mapAccumR@ does the same, but working from right to left instead. Its type is
561 the same as @mapAccumL@, though.
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
569 -> (acc, [y]) -- Final accumulator and result list
571 mapAccumR f b [] = (b, [])
572 mapAccumR f b (x:xs) = (b'', x':xs') where
574 (b', xs') = mapAccumR f b xs
577 Here is the bi-directional version, that works from both left and right.
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
587 -> (accl, accr, [y]) -- Final accumulators and result list
589 mapAccumB f a b [] = (a,b,[])
590 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
592 (a',b'',y) = f a b' x
593 (a'',b',ys) = mapAccumB f a' b xs
596 A combination of foldl with zip. It works with equal length lists.
599 foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
601 foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
604 Count the number of times a predicate is true
607 count :: (a -> Bool) -> [a] -> Int
609 count p (x:xs) | p x = 1 + count p xs
610 | otherwise = count p xs
614 %************************************************************************
616 \subsection[Utils-comparison]{Comparisons}
618 %************************************************************************
621 thenCmp :: Ordering -> Ordering -> Ordering
622 {-# INLINE thenCmp #-}
624 thenCmp other any = other
626 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
627 -- `cmpList' uses a user-specified comparer
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 }
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
643 postfixMatch :: Eq a => [a] -> [a] -> Bool
644 postfixMatch pat str = prefixMatch (reverse pat) (reverse str)
647 %************************************************************************
649 \subsection[Utils-pairs]{Pairs}
651 %************************************************************************
653 The following are curried versions of @fst@ and @snd@.
656 cfst :: a -> b -> a -- stranal-sem only (Note)
660 The following provide us higher order functions that, when applied
661 to a function, operate on pairs.
664 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
665 applyToPair (f,g) (x,y) = (f x, g y)
667 applyToFst :: (a -> c) -> (a,b)-> (c,b)
668 applyToFst f (x,y) = (f x,y)
670 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
671 applyToSnd f (x,y) = (x,f y)
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
680 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
681 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
686 seqList :: [a] -> b -> b
688 seqList :: (Eval a) => [a] -> b -> b
691 seqList (x:xs) b = x `seq` seqList xs b
693 #if __HASKELL1__ <= 4
694 ($!) :: (Eval a) => (a -> b) -> a -> b
700 #if __GLASGOW_HASKELL__ < 402
701 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
702 bracket before after thing = do
704 r <- (thing a) `catch` (\err -> after a >> fail err)
713 global :: a -> IORef a
714 global a = unsafePerformIO (newIORef a)
720 #if __GLASGOW_HASKELL__ <= 408
722 ioErrors = justIoErrors
723 throwTo = raiseInThread
726 #ifdef mingw32_TARGET_OS
727 foreign import "_getpid" myProcessID :: IO Int
729 myProcessID :: IO Int
730 myProcessID = do hPutStrLn stderr "Warning:myProcessID"