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,
21 lengthExceeds, lengthIs, lengthAtLeast, listLengthCmp, atLength,
32 IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
34 IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
35 IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
37 -- transitive closures
41 mapAccumL, mapAccumR, mapAccumB,
44 takeList, dropList, splitAtList,
47 eqListBy, equalLength, compareLength,
48 thenCmp, cmpList, prefixMatch, suffixMatch,
54 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
55 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
60 #if __GLASGOW_HASKELL__ <= 408
68 #include "../includes/config.h"
69 #include "HsVersions.h"
71 import qualified List ( elem, notElem )
72 import List ( zipWith4 )
73 import Maybe ( Maybe(..) )
74 import Panic ( panic, trace )
75 import IOExts ( IORef, newIORef, unsafePerformIO )
77 #if __GLASGOW_HASKELL__ <= 408
78 import Exception ( catchIO, justIoErrors, raiseInThread )
84 %************************************************************************
86 \subsection{The Eager monad}
88 %************************************************************************
90 The @Eager@ monad is just an encoding of continuation-passing style,
91 used to allow you to express "do this and then that", mainly to avoid
92 space leaks. It's done with a type synonym to save bureaucracy.
97 type Eager ans a = (a -> ans) -> ans
99 runEager :: Eager a a -> a
100 runEager m = m (\x -> x)
102 appEager :: Eager ans a -> (a -> ans) -> ans
103 appEager m cont = m cont
105 thenEager :: Eager ans a -> (a -> Eager ans b) -> Eager ans b
106 thenEager m k cont = m (\r -> k r cont)
108 returnEager :: a -> Eager ans a
109 returnEager v cont = cont v
111 mapEager :: (a -> Eager ans b) -> [a] -> Eager ans [b]
112 mapEager f [] = returnEager []
113 mapEager f (x:xs) = f x `thenEager` \ y ->
114 mapEager f xs `thenEager` \ ys ->
119 %************************************************************************
121 \subsection{A for loop}
123 %************************************************************************
126 -- Compose a function with itself n times. (nth rather than twice)
127 nTimes :: Int -> (a -> a) -> (a -> a)
130 nTimes n f = f . nTimes (n-1) f
133 %************************************************************************
135 \subsection[Utils-lists]{General list processing}
137 %************************************************************************
139 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
140 are of equal length. Alastair Reid thinks this should only happen if
141 DEBUGging on; hey, why not?
144 zipEqual :: String -> [a] -> [b] -> [(a,b)]
145 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
146 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
147 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
151 zipWithEqual _ = zipWith
152 zipWith3Equal _ = zipWith3
153 zipWith4Equal _ = zipWith4
155 zipEqual msg [] [] = []
156 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
157 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
159 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
160 zipWithEqual msg _ [] [] = []
161 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
163 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
164 = z a b c : zipWith3Equal msg z as bs cs
165 zipWith3Equal msg _ [] [] [] = []
166 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
168 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
169 = z a b c d : zipWith4Equal msg z as bs cs ds
170 zipWith4Equal msg _ [] [] [] [] = []
171 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
176 -- zipLazy is lazy in the second list (observe the ~)
178 zipLazy :: [a] -> [b] -> [(a,b)]
180 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
185 stretchZipWith :: (a -> Bool) -> b -> (a->b->c) -> [a] -> [b] -> [c]
186 -- (stretchZipWith p z f xs ys) stretches ys by inserting z in
187 -- the places where p returns *True*
189 stretchZipWith p z f [] ys = []
190 stretchZipWith p z f (x:xs) ys
191 | p x = f x z : stretchZipWith p z f xs ys
192 | otherwise = case ys of
194 (y:ys) -> f x y : stretchZipWith p z f xs ys
199 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
201 mapAndUnzip f [] = ([],[])
205 (rs1, rs2) = mapAndUnzip f xs
209 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
211 mapAndUnzip3 f [] = ([],[],[])
212 mapAndUnzip3 f (x:xs)
215 (rs1, rs2, rs3) = mapAndUnzip3 f xs
217 (r1:rs1, r2:rs2, r3:rs3)
221 nOfThem :: Int -> a -> [a]
222 nOfThem n thing = replicate n thing
224 -- 'atLength atLen atEnd ls n' unravels list 'ls' to position 'n';
227 -- atLength atLenPred atEndPred ls n
228 -- | n < 0 = atLenPred n
229 -- | length ls < n = atEndPred (n - length ls)
230 -- | otherwise = atLenPred (drop n ls)
232 atLength :: ([a] -> b)
237 atLength atLenPred atEndPred ls n
238 | n < 0 = atEndPred n
239 | otherwise = go n ls
241 go n [] = atEndPred n
242 go 0 ls = atLenPred ls
243 go n (_:xs) = go (n-1) xs
246 lengthExceeds :: [a] -> Int -> Bool
247 -- (lengthExceeds xs n) = (length xs > n)
248 lengthExceeds = atLength notNull (const False)
250 lengthAtLeast :: [a] -> Int -> Bool
251 lengthAtLeast = atLength notNull (== 0)
253 lengthIs :: [a] -> Int -> Bool
254 lengthIs = atLength null (==0)
256 listLengthCmp :: [a] -> Int -> Ordering
257 listLengthCmp = atLength atLen atEnd
261 | x > 0 = LT -- not yet seen 'n' elts, so list length is < n.
267 isSingleton :: [a] -> Bool
268 isSingleton [x] = True
269 isSingleton _ = False
271 notNull :: [a] -> Bool
284 snocView :: [a] -> ([a], a) -- Split off the last element
285 snocView xs = go xs []
287 go [x] acc = (reverse acc, x)
288 go (x:xs) acc = go xs (x:acc)
291 Debugging/specialising versions of \tr{elem} and \tr{notElem}
294 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
297 isIn msg x ys = elem__ x ys
298 isn'tIn msg x ys = notElem__ x ys
300 --these are here to be SPECIALIZEd (automagically)
302 elem__ x (y:ys) = x==y || elem__ x ys
304 notElem__ x [] = True
305 notElem__ x (y:ys) = x /= y && notElem__ x ys
309 = elem (_ILIT 0) x ys
313 | i ># _ILIT 100 = trace ("Over-long elem in " ++ msg) $
315 | otherwise = x == y || elem (i +# _ILIT(1)) x ys
318 = notElem (_ILIT 0) x ys
320 notElem i x [] = True
322 | i ># _ILIT 100 = trace ("Over-long notElem in " ++ msg) $
323 x `List.notElem` (y:ys)
324 | otherwise = x /= y && notElem (i +# _ILIT(1)) x ys
328 %************************************************************************
330 \subsection[Utils-sorting]{Sorting}
332 %************************************************************************
334 %************************************************************************
336 \subsubsection[Utils-quicksorting]{Quicksorts}
338 %************************************************************************
343 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
344 quicksort :: (a -> a -> Bool) -- Less-than predicate
346 -> [a] -- Result list in increasing order
349 quicksort lt [x] = [x]
350 quicksort lt (x:xs) = split x [] [] xs
352 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
353 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
354 | True = split x lo (y:hi) ys
358 Quicksort variant from Lennart's Haskell-library contribution. This
359 is a {\em stable} sort.
362 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
364 sortLt :: (a -> a -> Bool) -- Less-than predicate
366 -> [a] -- Result list
368 sortLt lt l = qsort lt l []
370 -- qsort is stable and does not concatenate.
371 qsort :: (a -> a -> Bool) -- Less-than predicate
372 -> [a] -- xs, Input list
373 -> [a] -- r, Concatenate this list to the sorted input list
374 -> [a] -- Result = sort xs ++ r
378 qsort lt (x:xs) r = qpart lt x xs [] [] r
380 -- qpart partitions and sorts the sublists
381 -- rlt contains things less than x,
382 -- rge contains the ones greater than or equal to x.
383 -- Both have equal elements reversed with respect to the original list.
385 qpart lt x [] rlt rge r =
386 -- rlt and rge are in reverse order and must be sorted with an
387 -- anti-stable sorting
388 rqsort lt rlt (x : rqsort lt rge r)
390 qpart lt x (y:ys) rlt rge r =
393 qpart lt x ys (y:rlt) rge r
396 qpart lt x ys rlt (y:rge) r
398 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
400 rqsort lt [x] r = x:r
401 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
403 rqpart lt x [] rle rgt r =
404 qsort lt rle (x : qsort lt rgt r)
406 rqpart lt x (y:ys) rle rgt r =
409 rqpart lt x ys rle (y:rgt) r
412 rqpart lt x ys (y:rle) rgt r
415 %************************************************************************
417 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
419 %************************************************************************
423 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
425 mergesort cmp xs = merge_lists (split_into_runs [] xs)
427 a `le` b = case cmp a b of { LT -> True; EQ -> True; GT -> False }
428 a `ge` b = case cmp a b of { LT -> False; EQ -> True; GT -> True }
430 split_into_runs [] [] = []
431 split_into_runs run [] = [run]
432 split_into_runs [] (x:xs) = split_into_runs [x] xs
433 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
434 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
435 | True = rl : (split_into_runs [x] xs)
438 merge_lists (x:xs) = merge x (merge_lists xs)
442 merge xl@(x:xs) yl@(y:ys)
444 EQ -> x : y : (merge xs ys)
445 LT -> x : (merge xs yl)
446 GT -> y : (merge xl ys)
450 %************************************************************************
452 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
454 %************************************************************************
457 Date: Mon, 3 May 93 20:45:23 +0200
458 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
459 To: partain@dcs.gla.ac.uk
460 Subject: natural merge sort beats quick sort [ and it is prettier ]
462 Here is a piece of Haskell code that I'm rather fond of. See it as an
463 attempt to get rid of the ridiculous quick-sort routine. group is
464 quite useful by itself I think it was John's idea originally though I
465 believe the lazy version is due to me [surprisingly complicated].
466 gamma [used to be called] is called gamma because I got inspired by
467 the Gamma calculus. It is not very close to the calculus but does
468 behave less sequentially than both foldr and foldl. One could imagine
469 a version of gamma that took a unit element as well thereby avoiding
470 the problem with empty lists.
472 I've tried this code against
474 1) insertion sort - as provided by haskell
475 2) the normal implementation of quick sort
476 3) a deforested version of quick sort due to Jan Sparud
477 4) a super-optimized-quick-sort of Lennart's
479 If the list is partially sorted both merge sort and in particular
480 natural merge sort wins. If the list is random [ average length of
481 rising subsequences = approx 2 ] mergesort still wins and natural
482 merge sort is marginally beaten by Lennart's soqs. The space
483 consumption of merge sort is a bit worse than Lennart's quick sort
484 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
485 fpca article ] isn't used because of group.
492 group :: (a -> a -> Bool) -> [a] -> [[a]]
495 Date: Mon, 12 Feb 1996 15:09:41 +0000
496 From: Andy Gill <andy@dcs.gla.ac.uk>
498 Here is a `better' definition of group.
501 group p (x:xs) = group' xs x x (x :)
503 group' [] _ _ s = [s []]
504 group' (x:xs) x_min x_max s
505 | not (x `p` x_max) = group' xs x_min x (s . (x :))
506 | x `p` x_min = group' xs x x_max ((x :) . s)
507 | otherwise = s [] : group' xs x x (x :)
509 -- This one works forwards *and* backwards, as well as also being
510 -- faster that the one in Util.lhs.
515 let ((h1:t1):tt1) = group p xs
516 (t,tt) = if null xs then ([],[]) else
517 if x `p` h1 then (h1:t1,tt1) else
522 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
523 generalMerge p xs [] = xs
524 generalMerge p [] ys = ys
525 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
526 | otherwise = y : generalMerge p (x:xs) ys
528 -- gamma is now called balancedFold
530 balancedFold :: (a -> a -> a) -> [a] -> a
531 balancedFold f [] = error "can't reduce an empty list using balancedFold"
532 balancedFold f [x] = x
533 balancedFold f l = balancedFold f (balancedFold' f l)
535 balancedFold' :: (a -> a -> a) -> [a] -> [a]
536 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
537 balancedFold' f xs = xs
539 generalMergeSort p [] = []
540 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
542 generalNaturalMergeSort p [] = []
543 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
545 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
547 mergeSort = generalMergeSort (<=)
548 naturalMergeSort = generalNaturalMergeSort (<=)
550 mergeSortLe le = generalMergeSort le
551 naturalMergeSortLe le = generalNaturalMergeSort le
554 %************************************************************************
556 \subsection[Utils-transitive-closure]{Transitive closure}
558 %************************************************************************
560 This algorithm for transitive closure is straightforward, albeit quadratic.
563 transitiveClosure :: (a -> [a]) -- Successor function
564 -> (a -> a -> Bool) -- Equality predicate
566 -> [a] -- The transitive closure
568 transitiveClosure succ eq xs
572 go done (x:xs) | x `is_in` done = go done xs
573 | otherwise = go (x:done) (succ x ++ xs)
576 x `is_in` (y:ys) | eq x y = True
577 | otherwise = x `is_in` ys
580 %************************************************************************
582 \subsection[Utils-accum]{Accumulating}
584 %************************************************************************
586 @mapAccumL@ behaves like a combination
587 of @map@ and @foldl@;
588 it applies a function to each element of a list, passing an accumulating
589 parameter from left to right, and returning a final value of this
590 accumulator together with the new list.
593 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
594 -- and accumulator, returning new
595 -- accumulator and elt of result list
596 -> acc -- Initial accumulator
598 -> (acc, [y]) -- Final accumulator and result list
600 mapAccumL f b [] = (b, [])
601 mapAccumL f b (x:xs) = (b'', x':xs') where
603 (b'', xs') = mapAccumL f b' xs
606 @mapAccumR@ does the same, but working from right to left instead. Its type is
607 the same as @mapAccumL@, though.
610 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
611 -- and accumulator, returning new
612 -- accumulator and elt of result list
613 -> acc -- Initial accumulator
615 -> (acc, [y]) -- Final accumulator and result list
617 mapAccumR f b [] = (b, [])
618 mapAccumR f b (x:xs) = (b'', x':xs') where
620 (b', xs') = mapAccumR f b xs
623 Here is the bi-directional version, that works from both left and right.
626 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
627 -- Function of elt of input list
628 -- and accumulator, returning new
629 -- accumulator and elt of result list
630 -> accl -- Initial accumulator from left
631 -> accr -- Initial accumulator from right
633 -> (accl, accr, [y]) -- Final accumulators and result list
635 mapAccumB f a b [] = (a,b,[])
636 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
638 (a',b'',y) = f a b' x
639 (a'',b',ys) = mapAccumB f a' b xs
642 A strict version of foldl.
645 foldl' :: (a -> b -> a) -> a -> [b] -> a
646 foldl' f z xs = lgo z xs
649 lgo z (x:xs) = (lgo $! (f z x)) xs
652 A combination of foldl with zip. It works with equal length lists.
655 foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
657 foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
660 Count the number of times a predicate is true
663 count :: (a -> Bool) -> [a] -> Int
665 count p (x:xs) | p x = 1 + count p xs
666 | otherwise = count p xs
669 @splitAt@, @take@, and @drop@ but with length of another
670 list giving the break-off point:
673 takeList :: [b] -> [a] -> [a]
678 (y:ys) -> y : takeList xs ys
680 dropList :: [b] -> [a] -> [a]
682 dropList _ xs@[] = xs
683 dropList (_:xs) (_:ys) = dropList xs ys
686 splitAtList :: [b] -> [a] -> ([a], [a])
687 splitAtList [] xs = ([], xs)
688 splitAtList _ xs@[] = (xs, xs)
689 splitAtList (_:xs) (y:ys) = (y:ys', ys'')
691 (ys', ys'') = splitAtList xs ys
696 %************************************************************************
698 \subsection[Utils-comparison]{Comparisons}
700 %************************************************************************
703 eqListBy :: (a->a->Bool) -> [a] -> [a] -> Bool
704 eqListBy eq [] [] = True
705 eqListBy eq (x:xs) (y:ys) = eq x y && eqListBy eq xs ys
706 eqListBy eq xs ys = False
708 equalLength :: [a] -> [b] -> Bool
709 equalLength [] [] = True
710 equalLength (_:xs) (_:ys) = equalLength xs ys
711 equalLength xs ys = False
713 compareLength :: [a] -> [b] -> Ordering
714 compareLength [] [] = EQ
715 compareLength (_:xs) (_:ys) = compareLength xs ys
716 compareLength [] _ys = LT
717 compareLength _xs [] = GT
719 thenCmp :: Ordering -> Ordering -> Ordering
720 {-# INLINE thenCmp #-}
722 thenCmp other any = other
724 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
725 -- `cmpList' uses a user-specified comparer
727 cmpList cmp [] [] = EQ
728 cmpList cmp [] _ = LT
729 cmpList cmp _ [] = GT
730 cmpList cmp (a:as) (b:bs)
731 = case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
735 prefixMatch :: Eq a => [a] -> [a] -> Bool
736 prefixMatch [] _str = True
737 prefixMatch _pat [] = False
738 prefixMatch (p:ps) (s:ss) | p == s = prefixMatch ps ss
741 suffixMatch :: Eq a => [a] -> [a] -> Bool
742 suffixMatch pat str = prefixMatch (reverse pat) (reverse str)
745 %************************************************************************
747 \subsection[Utils-pairs]{Pairs}
749 %************************************************************************
751 The following are curried versions of @fst@ and @snd@.
754 cfst :: a -> b -> a -- stranal-sem only (Note)
758 The following provide us higher order functions that, when applied
759 to a function, operate on pairs.
762 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
763 applyToPair (f,g) (x,y) = (f x, g y)
765 applyToFst :: (a -> c) -> (a,b)-> (c,b)
766 applyToFst f (x,y) = (f x,y)
768 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
769 applyToSnd f (x,y) = (x,f y)
771 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
772 foldPair fg ab [] = ab
773 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
774 where (u,v) = foldPair fg ab abs
778 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
779 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
783 seqList :: [a] -> b -> b
785 seqList (x:xs) b = x `seq` seqList xs b
791 global :: a -> IORef a
792 global a = unsafePerformIO (newIORef a)
798 #if __GLASGOW_HASKELL__ <= 408
800 ioErrors = justIoErrors
801 throwTo = raiseInThread