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,
31 IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
33 IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
34 IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
36 -- transitive closures
40 mapAccumL, mapAccumR, mapAccumB,
44 thenCmp, cmpList, prefixMatch, suffixMatch,
50 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
51 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
56 #if __GLASGOW_HASKELL__ <= 408
64 #include "../includes/config.h"
65 #include "HsVersions.h"
67 import List ( zipWith4 )
68 import Maybe ( Maybe(..) )
69 import Panic ( panic )
70 import IOExts ( IORef, newIORef, unsafePerformIO )
72 #if __GLASGOW_HASKELL__ <= 408
73 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
128 %************************************************************************
130 \subsection{Maybe-ery}
132 %************************************************************************
135 unJust :: String -> Maybe a -> a
136 unJust who (Just x) = x
137 unJust who Nothing = panic ("unJust of Nothing, called by " ++ who)
140 %************************************************************************
142 \subsection[Utils-lists]{General list processing}
144 %************************************************************************
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?
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]
158 zipWithEqual _ = zipWith
159 zipWith3Equal _ = zipWith3
160 zipWith4Equal _ = zipWith4
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)
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)
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)
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)
183 -- zipLazy is lazy in the second list (observe the ~)
185 zipLazy :: [a] -> [b] -> [(a,b)]
187 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
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*
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
201 (y:ys) -> f x y : stretchZipWith p z f xs ys
206 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
208 mapAndUnzip f [] = ([],[])
212 (rs1, rs2) = mapAndUnzip f xs
216 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
218 mapAndUnzip3 f [] = ([],[],[])
219 mapAndUnzip3 f (x:xs)
222 (rs1, rs2, rs3) = mapAndUnzip3 f xs
224 (r1:rs1, r2:rs2, r3:rs3)
228 nOfThem :: Int -> a -> [a]
229 nOfThem n thing = replicate n thing
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
236 isSingleton :: [a] -> Bool
237 isSingleton [x] = True
238 isSingleton _ = False
249 snocView :: [a] -> ([a], a) -- Split off the last element
250 snocView xs = go xs []
252 go [x] acc = (reverse acc, x)
253 go (x:xs) acc = go xs (x:acc)
256 Debugging/specialising versions of \tr{elem} and \tr{notElem}
259 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
262 isIn msg x ys = elem__ x ys
263 isn'tIn msg x ys = notElem__ x ys
265 --these are here to be SPECIALIZEd (automagically)
267 elem__ x (y:ys) = x==y || elem__ x ys
269 notElem__ x [] = True
270 notElem__ x (y:ys) = x /= y && notElem__ x ys
274 = elem (_ILIT 0) x ys
278 | i ># _ILIT 100 = panic ("Over-long elem in: " ++ msg)
279 | otherwise = x == y || elem (i +# _ILIT(1)) x ys
282 = notElem (_ILIT 0) x ys
284 notElem i x [] = True
286 | i ># _ILIT 100 = panic ("Over-long notElem in: " ++ msg)
287 | otherwise = x /= y && notElem (i +# _ILIT(1)) x ys
293 %************************************************************************
295 \subsection[Utils-sorting]{Sorting}
297 %************************************************************************
299 %************************************************************************
301 \subsubsection[Utils-quicksorting]{Quicksorts}
303 %************************************************************************
308 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
309 quicksort :: (a -> a -> Bool) -- Less-than predicate
311 -> [a] -- Result list in increasing order
314 quicksort lt [x] = [x]
315 quicksort lt (x:xs) = split x [] [] xs
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
323 Quicksort variant from Lennart's Haskell-library contribution. This
324 is a {\em stable} sort.
327 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
329 sortLt :: (a -> a -> Bool) -- Less-than predicate
331 -> [a] -- Result list
333 sortLt lt l = qsort lt l []
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
343 qsort lt (x:xs) r = qpart lt x xs [] [] r
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.
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)
355 qpart lt x (y:ys) rlt rge r =
358 qpart lt x ys (y:rlt) rge r
361 qpart lt x ys rlt (y:rge) r
363 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
365 rqsort lt [x] r = x:r
366 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
368 rqpart lt x [] rle rgt r =
369 qsort lt rle (x : qsort lt rgt r)
371 rqpart lt x (y:ys) rle rgt r =
374 rqpart lt x ys rle (y:rgt) r
377 rqpart lt x ys (y:rle) rgt r
380 %************************************************************************
382 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
384 %************************************************************************
388 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
390 mergesort cmp xs = merge_lists (split_into_runs [] xs)
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 }
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)
403 merge_lists (x:xs) = merge x (merge_lists xs)
407 merge xl@(x:xs) yl@(y:ys)
409 EQ -> x : y : (merge xs ys)
410 LT -> x : (merge xs yl)
411 GT -> y : (merge xl ys)
415 %************************************************************************
417 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
419 %************************************************************************
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 ]
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.
437 I've tried this code against
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
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.
457 group :: (a -> a -> Bool) -> [a] -> [[a]]
460 Date: Mon, 12 Feb 1996 15:09:41 +0000
461 From: Andy Gill <andy@dcs.gla.ac.uk>
463 Here is a `better' definition of group.
466 group p (x:xs) = group' xs x x (x :)
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 :)
474 -- This one works forwards *and* backwards, as well as also being
475 -- faster that the one in Util.lhs.
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
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
493 -- gamma is now called balancedFold
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)
500 balancedFold' :: (a -> a -> a) -> [a] -> [a]
501 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
502 balancedFold' f xs = xs
504 generalMergeSort p [] = []
505 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
507 generalNaturalMergeSort p [] = []
508 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
510 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
512 mergeSort = generalMergeSort (<=)
513 naturalMergeSort = generalNaturalMergeSort (<=)
515 mergeSortLe le = generalMergeSort le
516 naturalMergeSortLe le = generalNaturalMergeSort le
519 %************************************************************************
521 \subsection[Utils-transitive-closure]{Transitive closure}
523 %************************************************************************
525 This algorithm for transitive closure is straightforward, albeit quadratic.
528 transitiveClosure :: (a -> [a]) -- Successor function
529 -> (a -> a -> Bool) -- Equality predicate
531 -> [a] -- The transitive closure
533 transitiveClosure succ eq xs
537 go done (x:xs) | x `is_in` done = go done xs
538 | otherwise = go (x:done) (succ x ++ xs)
541 x `is_in` (y:ys) | eq x y = True
542 | otherwise = x `is_in` ys
545 %************************************************************************
547 \subsection[Utils-accum]{Accumulating}
549 %************************************************************************
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.
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
563 -> (acc, [y]) -- Final accumulator and result list
565 mapAccumL f b [] = (b, [])
566 mapAccumL f b (x:xs) = (b'', x':xs') where
568 (b'', xs') = mapAccumL f b' xs
571 @mapAccumR@ does the same, but working from right to left instead. Its type is
572 the same as @mapAccumL@, though.
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
580 -> (acc, [y]) -- Final accumulator and result list
582 mapAccumR f b [] = (b, [])
583 mapAccumR f b (x:xs) = (b'', x':xs') where
585 (b', xs') = mapAccumR f b xs
588 Here is the bi-directional version, that works from both left and right.
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
598 -> (accl, accr, [y]) -- Final accumulators and result list
600 mapAccumB f a b [] = (a,b,[])
601 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
603 (a',b'',y) = f a b' x
604 (a'',b',ys) = mapAccumB f a' b xs
607 A strict version of foldl.
610 foldl' :: (a -> b -> a) -> a -> [b] -> a
611 foldl' f z xs = lgo z xs
614 lgo z (x:xs) = (lgo $! (f z x)) xs
617 A combination of foldl with zip. It works with equal length lists.
620 foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
622 foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
625 Count the number of times a predicate is true
628 count :: (a -> Bool) -> [a] -> Int
630 count p (x:xs) | p x = 1 + count p xs
631 | otherwise = count p xs
635 %************************************************************************
637 \subsection[Utils-comparison]{Comparisons}
639 %************************************************************************
642 thenCmp :: Ordering -> Ordering -> Ordering
643 {-# INLINE thenCmp #-}
645 thenCmp other any = other
647 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
648 -- `cmpList' uses a user-specified comparer
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 }
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
664 suffixMatch :: Eq a => [a] -> [a] -> Bool
665 suffixMatch pat str = prefixMatch (reverse pat) (reverse str)
668 %************************************************************************
670 \subsection[Utils-pairs]{Pairs}
672 %************************************************************************
674 The following are curried versions of @fst@ and @snd@.
677 cfst :: a -> b -> a -- stranal-sem only (Note)
681 The following provide us higher order functions that, when applied
682 to a function, operate on pairs.
685 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
686 applyToPair (f,g) (x,y) = (f x, g y)
688 applyToFst :: (a -> c) -> (a,b)-> (c,b)
689 applyToFst f (x,y) = (f x,y)
691 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
692 applyToSnd f (x,y) = (x,f y)
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
701 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
702 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
706 seqList :: [a] -> b -> b
708 seqList (x:xs) b = x `seq` seqList xs b
714 global :: a -> IORef a
715 global a = unsafePerformIO (newIORef a)
721 #if __GLASGOW_HASKELL__ <= 408
723 ioErrors = justIoErrors
724 throwTo = raiseInThread