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,
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)
70 #ifdef USE_FAST_STRINGS
76 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
77 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
81 #if defined(COMPILING_GHC)
82 , panic, panic#, pprPanic, pprPanic#, pprError, pprTrace
84 #endif {- COMPILING_GHC -}
86 -- and to make the interface self-sufficient...
88 # if defined(COMPILING_GHC)
89 , Maybe(..){-.. for pragmas...-}, PrettyRep, Pretty(..)
97 #if defined(COMPILING_GHC)
99 CHK_Ubiq() -- debugging consistency check
104 import Maybes ( Maybe(..) )
108 %************************************************************************
110 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
112 %************************************************************************
114 This is our own idea:
116 #ifndef __GLASGOW_HASKELL__
117 data TAG_ = LT_ | EQ_ | GT_
119 tagCmp_ :: Ord a => a -> a -> TAG_
120 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
124 %************************************************************************
126 \subsection[Utils-lists]{General list processing}
128 %************************************************************************
130 Quantifiers are not standard in Haskell. The following fill in the gap.
133 forall :: (a -> Bool) -> [a] -> Bool
134 forall pred [] = True
135 forall pred (x:xs) = pred x && forall pred xs
137 exists :: (a -> Bool) -> [a] -> Bool
138 exists pred [] = False
139 exists pred (x:xs) = pred x || exists pred xs
142 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
143 are of equal length. Alastair Reid thinks this should only happen if
144 DEBUGging on; hey, why not?
147 zipEqual :: [a] -> [b] -> [(a,b)]
148 zipWithEqual :: (a->b->c) -> [a]->[b]->[c]
149 zipWith3Equal :: (a->b->c->d) -> [a]->[b]->[c]->[d]
150 zipWith4Equal :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
154 zipWithEqual = zipWith
155 zipWith3Equal = zipWith3
156 zipWith4Equal = zipWith4
159 zipEqual (a:as) (b:bs) = (a,b) : zipEqual as bs
160 zipEqual as bs = panic "zipEqual: unequal lists"
162 zipWithEqual z (a:as) (b:bs) = z a b : zipWithEqual z as bs
163 zipWithEqual _ [] [] = []
164 zipWithEqual _ _ _ = panic "zipWithEqual: unequal lists"
166 zipWith3Equal z (a:as) (b:bs) (c:cs)
167 = z a b c : zipWith3Equal z as bs cs
168 zipWith3Equal _ [] [] [] = []
169 zipWith3Equal _ _ _ _ = panic "zipWith3Equal: unequal lists"
171 zipWith4Equal z (a:as) (b:bs) (c:cs) (d:ds)
172 = z a b c d : zipWith4Equal z as bs cs ds
173 zipWith4Equal _ [] [] [] [] = []
174 zipWith4Equal _ _ _ _ _ = panic "zipWith4Equal: unequal lists"
179 -- zipLazy is lazy in the second list (observe the ~)
181 zipLazy :: [a] -> [b] -> [(a,b)]
183 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
187 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
189 mapAndUnzip f [] = ([],[])
193 (rs1, rs2) = mapAndUnzip f xs
199 nOfThem :: Int -> a -> [a]
200 nOfThem n thing = take n (repeat thing)
202 lengthExceeds :: [a] -> Int -> Bool
204 [] `lengthExceeds` n = 0 > n
205 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
207 isSingleton :: [a] -> Bool
209 isSingleton [x] = True
210 isSingleton _ = False
212 startsWith, endsWith :: String -> String -> Maybe String
214 startsWith [] str = Just str
215 startsWith (c:cs) (s:ss)
216 = if c /= s then Nothing else startsWith cs ss
219 = case (startsWith (reverse cs) (reverse ss)) of
221 Just rs -> Just (reverse rs)
224 Debugging/specialising versions of \tr{elem} and \tr{notElem}
226 #if defined(COMPILING_GHC)
227 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
230 isIn msg x ys = elem__ x ys
231 isn'tIn msg x ys = notElem__ x ys
233 --these are here to be SPECIALIZEd (automagically)
235 elem__ x (y:ys) = x==y || elem__ x ys
237 notElem__ x [] = True
238 notElem__ x (y:ys) = x /= y && notElem__ x ys
246 | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
247 | otherwise = x == y || elem (i _ADD_ ILIT(1)) x ys
250 = notElem ILIT(0) x ys
252 notElem i x [] = True
254 | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
255 | otherwise = x /= y && notElem (i _ADD_ ILIT(1)) x ys
259 #endif {- COMPILING_GHC -}
262 %************************************************************************
264 \subsection[Utils-assoc]{Association lists}
266 %************************************************************************
268 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
271 assoc :: (Eq a) => String -> [(a, b)] -> a -> b
273 assoc crash_msg lst key
275 then panic ("Failed in assoc: " ++ crash_msg)
277 where res = [ val | (key', val) <- lst, key == key']
280 %************************************************************************
282 \subsection[Utils-dups]{Duplicate-handling}
284 %************************************************************************
287 hasNoDups :: (Eq a) => [a] -> Bool
289 hasNoDups xs = f [] xs
291 f seen_so_far [] = True
292 f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
297 #if defined(COMPILING_GHC)
298 is_elem = isIn "hasNoDups"
305 equivClasses :: (a -> a -> TAG_) -- Comparison
309 equivClasses cmp stuff@[] = []
310 equivClasses cmp stuff@[item] = [stuff]
311 equivClasses cmp items
312 = runs eq (sortLt lt items)
314 eq a b = case cmp a b of { EQ_ -> True; _ -> False }
315 lt a b = case cmp a b of { LT_ -> True; _ -> False }
318 The first cases in @equivClasses@ above are just to cut to the point
321 @runs@ groups a list into a list of lists, each sublist being a run of
322 identical elements of the input list. It is passed a predicate @p@ which
323 tells when two elements are equal.
326 runs :: (a -> a -> Bool) -- Equality
331 runs p (x:xs) = case (span (p x) xs) of
332 (first, rest) -> (x:first) : (runs p rest)
336 removeDups :: (a -> a -> TAG_) -- Comparison function
338 -> ([a], -- List with no duplicates
339 [[a]]) -- List of duplicate groups. One representative from
340 -- each group appears in the first result
342 removeDups cmp [] = ([], [])
343 removeDups cmp [x] = ([x],[])
345 = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
348 collect_dups dups_so_far [x] = (dups_so_far, x)
349 collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
352 %************************************************************************
354 \subsection[Utils-sorting]{Sorting}
356 %************************************************************************
358 %************************************************************************
360 \subsubsection[Utils-quicksorting]{Quicksorts}
362 %************************************************************************
365 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
366 quicksort :: (a -> a -> Bool) -- Less-than predicate
368 -> [a] -- Result list in increasing order
371 quicksort lt [x] = [x]
372 quicksort lt (x:xs) = split x [] [] xs
374 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
375 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
376 | True = split x lo (y:hi) ys
379 Quicksort variant from Lennart's Haskell-library contribution. This
380 is a {\em stable} sort.
383 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
385 sortLt :: (a -> a -> Bool) -- Less-than predicate
387 -> [a] -- Result list
389 sortLt lt l = qsort lt l []
391 -- qsort is stable and does not concatenate.
392 qsort :: (a -> a -> Bool) -- Less-than predicate
393 -> [a] -- xs, Input list
394 -> [a] -- r, Concatenate this list to the sorted input list
395 -> [a] -- Result = sort xs ++ r
399 qsort lt (x:xs) r = qpart lt x xs [] [] r
401 -- qpart partitions and sorts the sublists
402 -- rlt contains things less than x,
403 -- rge contains the ones greater than or equal to x.
404 -- Both have equal elements reversed with respect to the original list.
406 qpart lt x [] rlt rge r =
407 -- rlt and rge are in reverse order and must be sorted with an
408 -- anti-stable sorting
409 rqsort lt rlt (x : rqsort lt rge r)
411 qpart lt x (y:ys) rlt rge r =
414 qpart lt x ys (y:rlt) rge r
417 qpart lt x ys rlt (y:rge) r
419 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
421 rqsort lt [x] r = x:r
422 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
424 rqpart lt x [] rle rgt r =
425 qsort lt rle (x : qsort lt rgt r)
427 rqpart lt x (y:ys) rle rgt r =
430 rqpart lt x ys rle (y:rgt) r
433 rqpart lt x ys (y:rle) rgt r
436 %************************************************************************
438 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
440 %************************************************************************
443 mergesort :: (a -> a -> TAG_) -> [a] -> [a]
445 mergesort cmp xs = merge_lists (split_into_runs [] xs)
447 a `le` b = case cmp a b of { LT_ -> True; EQ_ -> True; GT__ -> False }
448 a `ge` b = case cmp a b of { LT_ -> False; EQ_ -> True; GT__ -> True }
450 split_into_runs [] [] = []
451 split_into_runs run [] = [run]
452 split_into_runs [] (x:xs) = split_into_runs [x] xs
453 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
454 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
455 | True = rl : (split_into_runs [x] xs)
458 merge_lists (x:xs) = merge x (merge_lists xs)
462 merge xl@(x:xs) yl@(y:ys)
464 EQ_ -> x : y : (merge xs ys)
465 LT_ -> x : (merge xs yl)
466 GT__ -> y : (merge xl ys)
469 %************************************************************************
471 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
473 %************************************************************************
476 Date: Mon, 3 May 93 20:45:23 +0200
477 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
478 To: partain@dcs.gla.ac.uk
479 Subject: natural merge sort beats quick sort [ and it is prettier ]
481 Here is a piece of Haskell code that I'm rather fond of. See it as an
482 attempt to get rid of the ridiculous quick-sort routine. group is
483 quite useful by itself I think it was John's idea originally though I
484 believe the lazy version is due to me [surprisingly complicated].
485 gamma [used to be called] is called gamma because I got inspired by
486 the Gamma calculus. It is not very close to the calculus but does
487 behave less sequentially than both foldr and foldl. One could imagine
488 a version of gamma that took a unit element as well thereby avoiding
489 the problem with empty lists.
491 I've tried this code against
493 1) insertion sort - as provided by haskell
494 2) the normal implementation of quick sort
495 3) a deforested version of quick sort due to Jan Sparud
496 4) a super-optimized-quick-sort of Lennart's
498 If the list is partially sorted both merge sort and in particular
499 natural merge sort wins. If the list is random [ average length of
500 rising subsequences = approx 2 ] mergesort still wins and natural
501 merge sort is marginally beaten by Lennart's soqs. The space
502 consumption of merge sort is a bit worse than Lennart's quick sort
503 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
504 fpca article ] isn't used because of group.
511 group :: (a -> a -> Bool) -> [a] -> [[a]]
514 Date: Mon, 12 Feb 1996 15:09:41 +0000
515 From: Andy Gill <andy@dcs.gla.ac.uk>
517 Here is a `better' definition of group.
520 group p (x:xs) = group' xs x x (x :)
522 group' [] _ _ s = [s []]
523 group' (x:xs) x_min x_max s
524 | not (x `p` x_max) = group' xs x_min x (s . (x :))
525 | x `p` x_min = group' xs x x_max ((x :) . s)
526 | otherwise = s [] : group' xs x x (x :)
528 -- This one works forwards *and* backwards, as well as also being
529 -- faster that the one in Util.lhs.
534 let ((h1:t1):tt1) = group p xs
535 (t,tt) = if null xs then ([],[]) else
536 if x `p` h1 then (h1:t1,tt1) else
541 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
542 generalMerge p xs [] = xs
543 generalMerge p [] ys = ys
544 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
545 | otherwise = y : generalMerge p (x:xs) ys
547 -- gamma is now called balancedFold
549 balancedFold :: (a -> a -> a) -> [a] -> a
550 balancedFold f [] = error "can't reduce an empty list using balancedFold"
551 balancedFold f [x] = x
552 balancedFold f l = balancedFold f (balancedFold' f l)
554 balancedFold' :: (a -> a -> a) -> [a] -> [a]
555 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
556 balancedFold' f xs = xs
558 generalMergeSort p [] = []
559 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
561 generalNaturalMergeSort p [] = []
562 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
564 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
566 mergeSort = generalMergeSort (<=)
567 naturalMergeSort = generalNaturalMergeSort (<=)
569 mergeSortLe le = generalMergeSort le
570 naturalMergeSortLe le = generalNaturalMergeSort le
573 %************************************************************************
575 \subsection[Utils-transitive-closure]{Transitive closure}
577 %************************************************************************
579 This algorithm for transitive closure is straightforward, albeit quadratic.
582 transitiveClosure :: (a -> [a]) -- Successor function
583 -> (a -> a -> Bool) -- Equality predicate
585 -> [a] -- The transitive closure
587 transitiveClosure succ eq xs
591 do done (x:xs) | x `is_in` done = do done xs
592 | otherwise = do (x:done) (succ x ++ xs)
595 x `is_in` (y:ys) | eq x y = True
596 | otherwise = x `is_in` ys
599 %************************************************************************
601 \subsection[Utils-accum]{Accumulating}
603 %************************************************************************
605 @mapAccumL@ behaves like a combination
606 of @map@ and @foldl@;
607 it applies a function to each element of a list, passing an accumulating
608 parameter from left to right, and returning a final value of this
609 accumulator together with the new list.
612 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
613 -- and accumulator, returning new
614 -- accumulator and elt of result list
615 -> acc -- Initial accumulator
617 -> (acc, [y]) -- Final accumulator and result list
619 mapAccumL f b [] = (b, [])
620 mapAccumL f b (x:xs) = (b'', x':xs') where
622 (b'', xs') = mapAccumL f b' xs
625 @mapAccumR@ does the same, but working from right to left instead. Its type is
626 the same as @mapAccumL@, though.
629 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
630 -- and accumulator, returning new
631 -- accumulator and elt of result list
632 -> acc -- Initial accumulator
634 -> (acc, [y]) -- Final accumulator and result list
636 mapAccumR f b [] = (b, [])
637 mapAccumR f b (x:xs) = (b'', x':xs') where
639 (b', xs') = mapAccumR f b xs
642 Here is the bi-directional version, that works from both left and right.
645 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
646 -- Function of elt of input list
647 -- and accumulator, returning new
648 -- accumulator and elt of result list
649 -> accl -- Initial accumulator from left
650 -> accr -- Initial accumulator from right
652 -> (accl, accr, [y]) -- Final accumulators and result list
654 mapAccumB f a b [] = (a,b,[])
655 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
657 (a',b'',y) = f a b' x
658 (a'',b',ys) = mapAccumB f a' b xs
661 %************************************************************************
663 \subsection[Utils-comparison]{Comparisons}
665 %************************************************************************
667 See also @tagCmp_@ near the versions-compatibility section.
669 The Ord3 class will be subsumed into Ord in Haskell 1.3.
673 cmp :: a -> a -> TAG_
675 thenCmp :: TAG_ -> TAG_ -> TAG_
676 {-# INLINE thenCmp #-}
677 thenCmp EQ_ any = any
678 thenCmp other any = other
680 cmpList :: (a -> a -> TAG_) -> [a] -> [a] -> TAG_
681 -- `cmpList' uses a user-specified comparer
683 cmpList cmp [] [] = EQ_
684 cmpList cmp [] _ = LT_
685 cmpList cmp _ [] = GT_
686 cmpList cmp (a:as) (b:bs)
687 = case cmp a b of { EQ_ -> cmpList cmp as bs; xxx -> xxx }
691 instance Ord3 a => Ord3 [a] where
695 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
697 instance Ord3 a => Ord3 (Maybe a) where
698 cmp Nothing Nothing = EQ_
699 cmp Nothing (Just y) = LT_
700 cmp (Just x) Nothing = GT_
701 cmp (Just x) (Just y) = x `cmp` y
703 instance Ord3 Int where
704 cmp a b | a < b = LT_
710 cmpString :: String -> String -> TAG_
712 cmpString [] [] = EQ_
713 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
714 else if x < y then LT_
716 cmpString [] ys = LT_
717 cmpString xs [] = GT_
719 cmpString _ _ = panic# "cmpString"
723 #ifdef USE_FAST_STRINGS
724 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
727 = case (_tagCmp x y) of { _LT -> LT_ ; _EQ -> EQ_ ; _GT -> GT_ }
732 #ifndef USE_FAST_STRINGS
733 substr :: FAST_STRING -> Int -> Int -> FAST_STRING
736 = ASSERT (beg >= 0 && beg <= end)
737 take (end - beg + 1) (drop beg str)
741 %************************************************************************
743 \subsection[Utils-pairs]{Pairs}
745 %************************************************************************
747 The following are curried versions of @fst@ and @snd@.
750 cfst :: a -> b -> a -- stranal-sem only (Note)
754 The following provide us higher order functions that, when applied
755 to a function, operate on pairs.
758 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
759 applyToPair (f,g) (x,y) = (f x, g y)
761 applyToFst :: (a -> c) -> (a,b)-> (c,b)
762 applyToFst f (x,y) = (f x,y)
764 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
765 applyToSnd f (x,y) = (x,f y)
767 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
768 foldPair fg ab [] = ab
769 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
770 where (u,v) = foldPair fg ab abs
774 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
775 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
778 %************************************************************************
780 \subsection[Utils-errors]{Error handling}
782 %************************************************************************
785 #if defined(COMPILING_GHC)
786 panic x = error ("panic! (the `impossible' happened):\n\t"
788 ++ "Please report it as a compiler bug "
789 ++ "to glasgow-haskell-bugs@dcs.glasgow.ac.uk.\n\n" )
791 pprPanic heading pretty_msg = panic (heading++(ppShow 80 pretty_msg))
792 pprError heading pretty_msg = error (heading++(ppShow 80 pretty_msg))
793 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
795 -- #-versions because panic can't return an unboxed int, and that's
796 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
797 -- No, man -- Too Beautiful! (Will)
799 panic# :: String -> TAG_
800 panic# s = case (panic s) of () -> EQ_
802 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
804 assertPanic :: String -> Int -> a
805 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
807 #endif {- COMPILING_GHC -}