2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[Util]{Highly random utility functions}
7 #if defined(COMPILING_GHC)
8 # include "HsVersions.h"
9 # define IF_NOT_GHC(a) {--}
12 # define TAG_ _CMP_TAG
17 # define tagCmp_ _tagCmp
18 # define FAST_STRING String
19 # define ASSERT(x) {-nothing-}
20 # define IF_NOT_GHC(a) a
24 #ifndef __GLASGOW_HASKELL__
33 -- Haskell-version support
34 #ifndef __GLASGOW_HASKELL__
38 -- general list processing
39 IF_NOT_GHC(forall COMMA exists COMMA)
40 zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
42 mapAndUnzip, mapAndUnzip3,
43 nOfThem, lengthExceeds, isSingleton,
45 #if defined(COMPILING_GHC)
53 hasNoDups, equivClasses, runs, removeDups,
56 IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
58 IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
59 IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
61 -- transitive closures
65 mapAccumL, mapAccumR, mapAccumB,
68 Ord3(..), thenCmp, cmpList,
69 IF_NOT_GHC(cmpString COMMA)
73 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
74 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
78 #if defined(COMPILING_GHC)
79 , panic, panic#, pprPanic, pprPanic#, pprError, pprTrace
81 #endif {- COMPILING_GHC -}
85 #if defined(COMPILING_GHC)
87 CHK_Ubiq() -- debugging consistency check
88 IMPORT_1_3(List(zipWith4))
96 %************************************************************************
98 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
100 %************************************************************************
102 This is our own idea:
104 #ifndef __GLASGOW_HASKELL__
105 data TAG_ = LT_ | EQ_ | GT_
107 tagCmp_ :: Ord a => a -> a -> TAG_
108 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
112 %************************************************************************
114 \subsection[Utils-lists]{General list processing}
116 %************************************************************************
118 Quantifiers are not standard in Haskell. The following fill in the gap.
121 forall :: (a -> Bool) -> [a] -> Bool
122 forall pred [] = True
123 forall pred (x:xs) = pred x && forall pred xs
125 exists :: (a -> Bool) -> [a] -> Bool
126 exists pred [] = False
127 exists pred (x:xs) = pred x || exists pred xs
130 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
131 are of equal length. Alastair Reid thinks this should only happen if
132 DEBUGging on; hey, why not?
135 zipEqual :: String -> [a] -> [b] -> [(a,b)]
136 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
137 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
138 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
142 zipWithEqual _ = zipWith
143 zipWith3Equal _ = zipWith3
144 zipWith4Equal _ = zipWith4
146 zipEqual msg [] [] = []
147 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
148 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
150 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
151 zipWithEqual msg _ [] [] = []
152 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
154 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
155 = z a b c : zipWith3Equal msg z as bs cs
156 zipWith3Equal msg _ [] [] [] = []
157 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
159 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
160 = z a b c d : zipWith4Equal msg z as bs cs ds
161 zipWith4Equal msg _ [] [] [] [] = []
162 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
167 -- zipLazy is lazy in the second list (observe the ~)
169 zipLazy :: [a] -> [b] -> [(a,b)]
171 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
175 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
177 mapAndUnzip f [] = ([],[])
181 (rs1, rs2) = mapAndUnzip f xs
185 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
187 mapAndUnzip3 f [] = ([],[],[])
188 mapAndUnzip3 f (x:xs)
191 (rs1, rs2, rs3) = mapAndUnzip3 f xs
193 (r1:rs1, r2:rs2, r3:rs3)
197 nOfThem :: Int -> a -> [a]
198 nOfThem n thing = take n (repeat thing)
200 lengthExceeds :: [a] -> Int -> Bool
202 [] `lengthExceeds` n = 0 > n
203 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
205 isSingleton :: [a] -> Bool
207 isSingleton [x] = True
208 isSingleton _ = False
210 startsWith, endsWith :: String -> String -> Maybe String
212 startsWith [] str = Just str
213 startsWith (c:cs) (s:ss)
214 = if c /= s then Nothing else startsWith cs ss
215 startWith _ [] = Nothing
218 = case (startsWith (reverse cs) (reverse ss)) of
220 Just rs -> Just (reverse rs)
223 Debugging/specialising versions of \tr{elem} and \tr{notElem}
225 #if defined(COMPILING_GHC)
226 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
229 isIn msg x ys = elem__ x ys
230 isn'tIn msg x ys = notElem__ x ys
232 --these are here to be SPECIALIZEd (automagically)
234 elem__ x (y:ys) = x==y || elem__ x ys
236 notElem__ x [] = True
237 notElem__ x (y:ys) = x /= y && notElem__ x ys
245 | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
246 | otherwise = x == y || elem (i _ADD_ ILIT(1)) x ys
249 = notElem ILIT(0) x ys
251 notElem i x [] = True
253 | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
254 | otherwise = x /= y && notElem (i _ADD_ ILIT(1)) x ys
258 #endif {- COMPILING_GHC -}
261 %************************************************************************
263 \subsection[Utils-assoc]{Association lists}
265 %************************************************************************
267 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
270 assoc :: (Eq a) => String -> [(a, b)] -> a -> b
272 assoc crash_msg lst key
274 then panic ("Failed in assoc: " ++ crash_msg)
276 where res = [ val | (key', val) <- lst, key == key']
279 %************************************************************************
281 \subsection[Utils-dups]{Duplicate-handling}
283 %************************************************************************
286 hasNoDups :: (Eq a) => [a] -> Bool
288 hasNoDups xs = f [] xs
290 f seen_so_far [] = True
291 f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
296 #if defined(COMPILING_GHC)
297 is_elem = isIn "hasNoDups"
304 equivClasses :: (a -> a -> TAG_) -- Comparison
308 equivClasses cmp stuff@[] = []
309 equivClasses cmp stuff@[item] = [stuff]
310 equivClasses cmp items
311 = runs eq (sortLt lt items)
313 eq a b = case cmp a b of { EQ_ -> True; _ -> False }
314 lt a b = case cmp a b of { LT_ -> True; _ -> False }
317 The first cases in @equivClasses@ above are just to cut to the point
320 @runs@ groups a list into a list of lists, each sublist being a run of
321 identical elements of the input list. It is passed a predicate @p@ which
322 tells when two elements are equal.
325 runs :: (a -> a -> Bool) -- Equality
330 runs p (x:xs) = case (span (p x) xs) of
331 (first, rest) -> (x:first) : (runs p rest)
335 removeDups :: (a -> a -> TAG_) -- Comparison function
337 -> ([a], -- List with no duplicates
338 [[a]]) -- List of duplicate groups. One representative from
339 -- each group appears in the first result
341 removeDups cmp [] = ([], [])
342 removeDups cmp [x] = ([x],[])
344 = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
347 collect_dups dups_so_far [x] = (dups_so_far, x)
348 collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
351 %************************************************************************
353 \subsection[Utils-sorting]{Sorting}
355 %************************************************************************
357 %************************************************************************
359 \subsubsection[Utils-quicksorting]{Quicksorts}
361 %************************************************************************
364 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
365 quicksort :: (a -> a -> Bool) -- Less-than predicate
367 -> [a] -- Result list in increasing order
370 quicksort lt [x] = [x]
371 quicksort lt (x:xs) = split x [] [] xs
373 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
374 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
375 | True = split x lo (y:hi) ys
378 Quicksort variant from Lennart's Haskell-library contribution. This
379 is a {\em stable} sort.
382 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
384 sortLt :: (a -> a -> Bool) -- Less-than predicate
386 -> [a] -- Result list
388 sortLt lt l = qsort lt l []
390 -- qsort is stable and does not concatenate.
391 qsort :: (a -> a -> Bool) -- Less-than predicate
392 -> [a] -- xs, Input list
393 -> [a] -- r, Concatenate this list to the sorted input list
394 -> [a] -- Result = sort xs ++ r
398 qsort lt (x:xs) r = qpart lt x xs [] [] r
400 -- qpart partitions and sorts the sublists
401 -- rlt contains things less than x,
402 -- rge contains the ones greater than or equal to x.
403 -- Both have equal elements reversed with respect to the original list.
405 qpart lt x [] rlt rge r =
406 -- rlt and rge are in reverse order and must be sorted with an
407 -- anti-stable sorting
408 rqsort lt rlt (x : rqsort lt rge r)
410 qpart lt x (y:ys) rlt rge r =
413 qpart lt x ys (y:rlt) rge r
416 qpart lt x ys rlt (y:rge) r
418 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
420 rqsort lt [x] r = x:r
421 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
423 rqpart lt x [] rle rgt r =
424 qsort lt rle (x : qsort lt rgt r)
426 rqpart lt x (y:ys) rle rgt r =
429 rqpart lt x ys rle (y:rgt) r
432 rqpart lt x ys (y:rle) rgt r
435 %************************************************************************
437 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
439 %************************************************************************
442 mergesort :: (a -> a -> TAG_) -> [a] -> [a]
444 mergesort cmp xs = merge_lists (split_into_runs [] xs)
446 a `le` b = case cmp a b of { LT_ -> True; EQ_ -> True; GT__ -> False }
447 a `ge` b = case cmp a b of { LT_ -> False; EQ_ -> True; GT__ -> True }
449 split_into_runs [] [] = []
450 split_into_runs run [] = [run]
451 split_into_runs [] (x:xs) = split_into_runs [x] xs
452 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
453 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
454 | True = rl : (split_into_runs [x] xs)
457 merge_lists (x:xs) = merge x (merge_lists xs)
461 merge xl@(x:xs) yl@(y:ys)
463 EQ_ -> x : y : (merge xs ys)
464 LT_ -> x : (merge xs yl)
465 GT__ -> y : (merge xl ys)
468 %************************************************************************
470 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
472 %************************************************************************
475 Date: Mon, 3 May 93 20:45:23 +0200
476 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
477 To: partain@dcs.gla.ac.uk
478 Subject: natural merge sort beats quick sort [ and it is prettier ]
480 Here is a piece of Haskell code that I'm rather fond of. See it as an
481 attempt to get rid of the ridiculous quick-sort routine. group is
482 quite useful by itself I think it was John's idea originally though I
483 believe the lazy version is due to me [surprisingly complicated].
484 gamma [used to be called] is called gamma because I got inspired by
485 the Gamma calculus. It is not very close to the calculus but does
486 behave less sequentially than both foldr and foldl. One could imagine
487 a version of gamma that took a unit element as well thereby avoiding
488 the problem with empty lists.
490 I've tried this code against
492 1) insertion sort - as provided by haskell
493 2) the normal implementation of quick sort
494 3) a deforested version of quick sort due to Jan Sparud
495 4) a super-optimized-quick-sort of Lennart's
497 If the list is partially sorted both merge sort and in particular
498 natural merge sort wins. If the list is random [ average length of
499 rising subsequences = approx 2 ] mergesort still wins and natural
500 merge sort is marginally beaten by Lennart's soqs. The space
501 consumption of merge sort is a bit worse than Lennart's quick sort
502 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
503 fpca article ] isn't used because of group.
510 group :: (a -> a -> Bool) -> [a] -> [[a]]
513 Date: Mon, 12 Feb 1996 15:09:41 +0000
514 From: Andy Gill <andy@dcs.gla.ac.uk>
516 Here is a `better' definition of group.
519 group p (x:xs) = group' xs x x (x :)
521 group' [] _ _ s = [s []]
522 group' (x:xs) x_min x_max s
523 | not (x `p` x_max) = group' xs x_min x (s . (x :))
524 | x `p` x_min = group' xs x x_max ((x :) . s)
525 | otherwise = s [] : group' xs x x (x :)
527 -- This one works forwards *and* backwards, as well as also being
528 -- faster that the one in Util.lhs.
533 let ((h1:t1):tt1) = group p xs
534 (t,tt) = if null xs then ([],[]) else
535 if x `p` h1 then (h1:t1,tt1) else
540 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
541 generalMerge p xs [] = xs
542 generalMerge p [] ys = ys
543 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
544 | otherwise = y : generalMerge p (x:xs) ys
546 -- gamma is now called balancedFold
548 balancedFold :: (a -> a -> a) -> [a] -> a
549 balancedFold f [] = error "can't reduce an empty list using balancedFold"
550 balancedFold f [x] = x
551 balancedFold f l = balancedFold f (balancedFold' f l)
553 balancedFold' :: (a -> a -> a) -> [a] -> [a]
554 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
555 balancedFold' f xs = xs
557 generalMergeSort p [] = []
558 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
560 generalNaturalMergeSort p [] = []
561 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
563 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
565 mergeSort = generalMergeSort (<=)
566 naturalMergeSort = generalNaturalMergeSort (<=)
568 mergeSortLe le = generalMergeSort le
569 naturalMergeSortLe le = generalNaturalMergeSort le
572 %************************************************************************
574 \subsection[Utils-transitive-closure]{Transitive closure}
576 %************************************************************************
578 This algorithm for transitive closure is straightforward, albeit quadratic.
581 transitiveClosure :: (a -> [a]) -- Successor function
582 -> (a -> a -> Bool) -- Equality predicate
584 -> [a] -- The transitive closure
586 transitiveClosure succ eq xs
590 go done (x:xs) | x `is_in` done = go done xs
591 | otherwise = go (x:done) (succ x ++ xs)
594 x `is_in` (y:ys) | eq x y = True
595 | otherwise = x `is_in` ys
598 %************************************************************************
600 \subsection[Utils-accum]{Accumulating}
602 %************************************************************************
604 @mapAccumL@ behaves like a combination
605 of @map@ and @foldl@;
606 it applies a function to each element of a list, passing an accumulating
607 parameter from left to right, and returning a final value of this
608 accumulator together with the new list.
611 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
612 -- and accumulator, returning new
613 -- accumulator and elt of result list
614 -> acc -- Initial accumulator
616 -> (acc, [y]) -- Final accumulator and result list
618 mapAccumL f b [] = (b, [])
619 mapAccumL f b (x:xs) = (b'', x':xs') where
621 (b'', xs') = mapAccumL f b' xs
624 @mapAccumR@ does the same, but working from right to left instead. Its type is
625 the same as @mapAccumL@, though.
628 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
629 -- and accumulator, returning new
630 -- accumulator and elt of result list
631 -> acc -- Initial accumulator
633 -> (acc, [y]) -- Final accumulator and result list
635 mapAccumR f b [] = (b, [])
636 mapAccumR f b (x:xs) = (b'', x':xs') where
638 (b', xs') = mapAccumR f b xs
641 Here is the bi-directional version, that works from both left and right.
644 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
645 -- Function of elt of input list
646 -- and accumulator, returning new
647 -- accumulator and elt of result list
648 -> accl -- Initial accumulator from left
649 -> accr -- Initial accumulator from right
651 -> (accl, accr, [y]) -- Final accumulators and result list
653 mapAccumB f a b [] = (a,b,[])
654 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
656 (a',b'',y) = f a b' x
657 (a'',b',ys) = mapAccumB f a' b xs
660 %************************************************************************
662 \subsection[Utils-comparison]{Comparisons}
664 %************************************************************************
666 See also @tagCmp_@ near the versions-compatibility section.
668 The Ord3 class will be subsumed into Ord in Haskell 1.3.
672 cmp :: a -> a -> TAG_
674 thenCmp :: TAG_ -> TAG_ -> TAG_
675 {-# INLINE thenCmp #-}
676 thenCmp EQ_ any = any
677 thenCmp other any = other
679 cmpList :: (a -> a -> TAG_) -> [a] -> [a] -> TAG_
680 -- `cmpList' uses a user-specified comparer
682 cmpList cmp [] [] = EQ_
683 cmpList cmp [] _ = LT_
684 cmpList cmp _ [] = GT_
685 cmpList cmp (a:as) (b:bs)
686 = case cmp a b of { EQ_ -> cmpList cmp as bs; xxx -> xxx }
690 instance Ord3 a => Ord3 [a] where
694 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
696 instance Ord3 a => Ord3 (Maybe a) where
697 cmp Nothing Nothing = EQ_
698 cmp Nothing (Just y) = LT_
699 cmp (Just x) Nothing = GT_
700 cmp (Just x) (Just y) = x `cmp` y
702 instance Ord3 Int where
703 cmp a b | a < b = LT_
709 cmpString :: String -> String -> TAG_
711 cmpString [] [] = EQ_
712 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
713 else if x < y then LT_
715 cmpString [] ys = LT_
716 cmpString xs [] = GT_
718 cmpString _ _ = panic# "cmpString"
722 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
725 = case (_tagCmp x y) of { _LT -> LT_ ; _EQ -> EQ_ ; _GT -> GT_ }
728 %************************************************************************
730 \subsection[Utils-pairs]{Pairs}
732 %************************************************************************
734 The following are curried versions of @fst@ and @snd@.
737 cfst :: a -> b -> a -- stranal-sem only (Note)
741 The following provide us higher order functions that, when applied
742 to a function, operate on pairs.
745 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
746 applyToPair (f,g) (x,y) = (f x, g y)
748 applyToFst :: (a -> c) -> (a,b)-> (c,b)
749 applyToFst f (x,y) = (f x,y)
751 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
752 applyToSnd f (x,y) = (x,f y)
754 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
755 foldPair fg ab [] = ab
756 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
757 where (u,v) = foldPair fg ab abs
761 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
762 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
765 %************************************************************************
767 \subsection[Utils-errors]{Error handling}
769 %************************************************************************
772 #if defined(COMPILING_GHC)
773 panic x = error ("panic! (the `impossible' happened):\n\t"
775 ++ "Please report it as a compiler bug "
776 ++ "to glasgow-haskell-bugs@dcs.glasgow.ac.uk.\n\n" )
778 pprPanic heading pretty_msg = panic (heading++(ppShow 80 pretty_msg))
779 pprError heading pretty_msg = error (heading++(ppShow 80 pretty_msg))
780 #if __GLASGOW_HASKELL__ >= 200
781 pprTrace heading pretty_msg = GHCbase.trace (heading++(ppShow 80 pretty_msg))
783 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
786 -- #-versions because panic can't return an unboxed int, and that's
787 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
788 -- No, man -- Too Beautiful! (Will)
790 panic# :: String -> TAG_
791 panic# s = case (panic s) of () -> EQ_
793 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
795 assertPanic :: String -> Int -> a
796 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
798 #endif {- COMPILING_GHC -}