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(..) )
110 %************************************************************************
112 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
114 %************************************************************************
116 This is our own idea:
118 #ifndef __GLASGOW_HASKELL__
119 data TAG_ = LT_ | EQ_ | GT_
121 tagCmp_ :: Ord a => a -> a -> TAG_
122 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
126 %************************************************************************
128 \subsection[Utils-lists]{General list processing}
130 %************************************************************************
132 Quantifiers are not standard in Haskell. The following fill in the gap.
135 forall :: (a -> Bool) -> [a] -> Bool
136 forall pred [] = True
137 forall pred (x:xs) = pred x && forall pred xs
139 exists :: (a -> Bool) -> [a] -> Bool
140 exists pred [] = False
141 exists pred (x:xs) = pred x || exists pred xs
144 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
145 are of equal length. Alastair Reid thinks this should only happen if
146 DEBUGging on; hey, why not?
149 zipEqual :: String -> [a] -> [b] -> [(a,b)]
150 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
151 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
152 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
156 zipWithEqual _ = zipWith
157 zipWith3Equal _ = zipWith3
158 zipWith4Equal _ = zipWith4
160 zipEqual msg [] [] = []
161 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
162 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
164 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
165 zipWithEqual msg _ [] [] = []
166 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
168 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
169 = z a b c : zipWith3Equal msg z as bs cs
170 zipWith3Equal msg _ [] [] [] = []
171 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
173 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
174 = z a b c d : zipWith4Equal msg z as bs cs ds
175 zipWith4Equal msg _ [] [] [] [] = []
176 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
181 -- zipLazy is lazy in the second list (observe the ~)
183 zipLazy :: [a] -> [b] -> [(a,b)]
185 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
189 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
191 mapAndUnzip f [] = ([],[])
195 (rs1, rs2) = mapAndUnzip f xs
201 nOfThem :: Int -> a -> [a]
202 nOfThem n thing = take n (repeat thing)
204 lengthExceeds :: [a] -> Int -> Bool
206 [] `lengthExceeds` n = 0 > n
207 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
209 isSingleton :: [a] -> Bool
211 isSingleton [x] = True
212 isSingleton _ = False
214 startsWith, endsWith :: String -> String -> Maybe String
216 startsWith [] str = Just str
217 startsWith (c:cs) (s:ss)
218 = if c /= s then Nothing else startsWith cs ss
221 = case (startsWith (reverse cs) (reverse ss)) of
223 Just rs -> Just (reverse rs)
226 Debugging/specialising versions of \tr{elem} and \tr{notElem}
228 #if defined(COMPILING_GHC)
229 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
232 isIn msg x ys = elem__ x ys
233 isn'tIn msg x ys = notElem__ x ys
235 --these are here to be SPECIALIZEd (automagically)
237 elem__ x (y:ys) = x==y || elem__ x ys
239 notElem__ x [] = True
240 notElem__ x (y:ys) = x /= y && notElem__ x ys
248 | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
249 | otherwise = x == y || elem (i _ADD_ ILIT(1)) x ys
252 = notElem ILIT(0) x ys
254 notElem i x [] = True
256 | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
257 | otherwise = x /= y && notElem (i _ADD_ ILIT(1)) x ys
261 #endif {- COMPILING_GHC -}
264 %************************************************************************
266 \subsection[Utils-assoc]{Association lists}
268 %************************************************************************
270 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
273 assoc :: (Eq a) => String -> [(a, b)] -> a -> b
275 assoc crash_msg lst key
277 then panic ("Failed in assoc: " ++ crash_msg)
279 where res = [ val | (key', val) <- lst, key == key']
282 %************************************************************************
284 \subsection[Utils-dups]{Duplicate-handling}
286 %************************************************************************
289 hasNoDups :: (Eq a) => [a] -> Bool
291 hasNoDups xs = f [] xs
293 f seen_so_far [] = True
294 f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
299 #if defined(COMPILING_GHC)
300 is_elem = isIn "hasNoDups"
307 equivClasses :: (a -> a -> TAG_) -- Comparison
311 equivClasses cmp stuff@[] = []
312 equivClasses cmp stuff@[item] = [stuff]
313 equivClasses cmp items
314 = runs eq (sortLt lt items)
316 eq a b = case cmp a b of { EQ_ -> True; _ -> False }
317 lt a b = case cmp a b of { LT_ -> True; _ -> False }
320 The first cases in @equivClasses@ above are just to cut to the point
323 @runs@ groups a list into a list of lists, each sublist being a run of
324 identical elements of the input list. It is passed a predicate @p@ which
325 tells when two elements are equal.
328 runs :: (a -> a -> Bool) -- Equality
333 runs p (x:xs) = case (span (p x) xs) of
334 (first, rest) -> (x:first) : (runs p rest)
338 removeDups :: (a -> a -> TAG_) -- Comparison function
340 -> ([a], -- List with no duplicates
341 [[a]]) -- List of duplicate groups. One representative from
342 -- each group appears in the first result
344 removeDups cmp [] = ([], [])
345 removeDups cmp [x] = ([x],[])
347 = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
350 collect_dups dups_so_far [x] = (dups_so_far, x)
351 collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
354 %************************************************************************
356 \subsection[Utils-sorting]{Sorting}
358 %************************************************************************
360 %************************************************************************
362 \subsubsection[Utils-quicksorting]{Quicksorts}
364 %************************************************************************
367 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
368 quicksort :: (a -> a -> Bool) -- Less-than predicate
370 -> [a] -- Result list in increasing order
373 quicksort lt [x] = [x]
374 quicksort lt (x:xs) = split x [] [] xs
376 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
377 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
378 | True = split x lo (y:hi) ys
381 Quicksort variant from Lennart's Haskell-library contribution. This
382 is a {\em stable} sort.
385 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
387 sortLt :: (a -> a -> Bool) -- Less-than predicate
389 -> [a] -- Result list
391 sortLt lt l = qsort lt l []
393 -- qsort is stable and does not concatenate.
394 qsort :: (a -> a -> Bool) -- Less-than predicate
395 -> [a] -- xs, Input list
396 -> [a] -- r, Concatenate this list to the sorted input list
397 -> [a] -- Result = sort xs ++ r
401 qsort lt (x:xs) r = qpart lt x xs [] [] r
403 -- qpart partitions and sorts the sublists
404 -- rlt contains things less than x,
405 -- rge contains the ones greater than or equal to x.
406 -- Both have equal elements reversed with respect to the original list.
408 qpart lt x [] rlt rge r =
409 -- rlt and rge are in reverse order and must be sorted with an
410 -- anti-stable sorting
411 rqsort lt rlt (x : rqsort lt rge r)
413 qpart lt x (y:ys) rlt rge r =
416 qpart lt x ys (y:rlt) rge r
419 qpart lt x ys rlt (y:rge) r
421 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
423 rqsort lt [x] r = x:r
424 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
426 rqpart lt x [] rle rgt r =
427 qsort lt rle (x : qsort lt rgt r)
429 rqpart lt x (y:ys) rle rgt r =
432 rqpart lt x ys rle (y:rgt) r
435 rqpart lt x ys (y:rle) rgt r
438 %************************************************************************
440 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
442 %************************************************************************
445 mergesort :: (a -> a -> TAG_) -> [a] -> [a]
447 mergesort cmp xs = merge_lists (split_into_runs [] xs)
449 a `le` b = case cmp a b of { LT_ -> True; EQ_ -> True; GT__ -> False }
450 a `ge` b = case cmp a b of { LT_ -> False; EQ_ -> True; GT__ -> True }
452 split_into_runs [] [] = []
453 split_into_runs run [] = [run]
454 split_into_runs [] (x:xs) = split_into_runs [x] xs
455 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
456 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
457 | True = rl : (split_into_runs [x] xs)
460 merge_lists (x:xs) = merge x (merge_lists xs)
464 merge xl@(x:xs) yl@(y:ys)
466 EQ_ -> x : y : (merge xs ys)
467 LT_ -> x : (merge xs yl)
468 GT__ -> y : (merge xl ys)
471 %************************************************************************
473 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
475 %************************************************************************
478 Date: Mon, 3 May 93 20:45:23 +0200
479 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
480 To: partain@dcs.gla.ac.uk
481 Subject: natural merge sort beats quick sort [ and it is prettier ]
483 Here is a piece of Haskell code that I'm rather fond of. See it as an
484 attempt to get rid of the ridiculous quick-sort routine. group is
485 quite useful by itself I think it was John's idea originally though I
486 believe the lazy version is due to me [surprisingly complicated].
487 gamma [used to be called] is called gamma because I got inspired by
488 the Gamma calculus. It is not very close to the calculus but does
489 behave less sequentially than both foldr and foldl. One could imagine
490 a version of gamma that took a unit element as well thereby avoiding
491 the problem with empty lists.
493 I've tried this code against
495 1) insertion sort - as provided by haskell
496 2) the normal implementation of quick sort
497 3) a deforested version of quick sort due to Jan Sparud
498 4) a super-optimized-quick-sort of Lennart's
500 If the list is partially sorted both merge sort and in particular
501 natural merge sort wins. If the list is random [ average length of
502 rising subsequences = approx 2 ] mergesort still wins and natural
503 merge sort is marginally beaten by Lennart's soqs. The space
504 consumption of merge sort is a bit worse than Lennart's quick sort
505 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
506 fpca article ] isn't used because of group.
513 group :: (a -> a -> Bool) -> [a] -> [[a]]
516 Date: Mon, 12 Feb 1996 15:09:41 +0000
517 From: Andy Gill <andy@dcs.gla.ac.uk>
519 Here is a `better' definition of group.
522 group p (x:xs) = group' xs x x (x :)
524 group' [] _ _ s = [s []]
525 group' (x:xs) x_min x_max s
526 | not (x `p` x_max) = group' xs x_min x (s . (x :))
527 | x `p` x_min = group' xs x x_max ((x :) . s)
528 | otherwise = s [] : group' xs x x (x :)
530 -- This one works forwards *and* backwards, as well as also being
531 -- faster that the one in Util.lhs.
536 let ((h1:t1):tt1) = group p xs
537 (t,tt) = if null xs then ([],[]) else
538 if x `p` h1 then (h1:t1,tt1) else
543 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
544 generalMerge p xs [] = xs
545 generalMerge p [] ys = ys
546 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
547 | otherwise = y : generalMerge p (x:xs) ys
549 -- gamma is now called balancedFold
551 balancedFold :: (a -> a -> a) -> [a] -> a
552 balancedFold f [] = error "can't reduce an empty list using balancedFold"
553 balancedFold f [x] = x
554 balancedFold f l = balancedFold f (balancedFold' f l)
556 balancedFold' :: (a -> a -> a) -> [a] -> [a]
557 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
558 balancedFold' f xs = xs
560 generalMergeSort p [] = []
561 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
563 generalNaturalMergeSort p [] = []
564 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
566 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
568 mergeSort = generalMergeSort (<=)
569 naturalMergeSort = generalNaturalMergeSort (<=)
571 mergeSortLe le = generalMergeSort le
572 naturalMergeSortLe le = generalNaturalMergeSort le
575 %************************************************************************
577 \subsection[Utils-transitive-closure]{Transitive closure}
579 %************************************************************************
581 This algorithm for transitive closure is straightforward, albeit quadratic.
584 transitiveClosure :: (a -> [a]) -- Successor function
585 -> (a -> a -> Bool) -- Equality predicate
587 -> [a] -- The transitive closure
589 transitiveClosure succ eq xs
593 do done (x:xs) | x `is_in` done = do done xs
594 | otherwise = do (x:done) (succ x ++ xs)
597 x `is_in` (y:ys) | eq x y = True
598 | otherwise = x `is_in` ys
601 %************************************************************************
603 \subsection[Utils-accum]{Accumulating}
605 %************************************************************************
607 @mapAccumL@ behaves like a combination
608 of @map@ and @foldl@;
609 it applies a function to each element of a list, passing an accumulating
610 parameter from left to right, and returning a final value of this
611 accumulator together with the new list.
614 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
615 -- and accumulator, returning new
616 -- accumulator and elt of result list
617 -> acc -- Initial accumulator
619 -> (acc, [y]) -- Final accumulator and result list
621 mapAccumL f b [] = (b, [])
622 mapAccumL f b (x:xs) = (b'', x':xs') where
624 (b'', xs') = mapAccumL f b' xs
627 @mapAccumR@ does the same, but working from right to left instead. Its type is
628 the same as @mapAccumL@, though.
631 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
632 -- and accumulator, returning new
633 -- accumulator and elt of result list
634 -> acc -- Initial accumulator
636 -> (acc, [y]) -- Final accumulator and result list
638 mapAccumR f b [] = (b, [])
639 mapAccumR f b (x:xs) = (b'', x':xs') where
641 (b', xs') = mapAccumR f b xs
644 Here is the bi-directional version, that works from both left and right.
647 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
648 -- Function of elt of input list
649 -- and accumulator, returning new
650 -- accumulator and elt of result list
651 -> accl -- Initial accumulator from left
652 -> accr -- Initial accumulator from right
654 -> (accl, accr, [y]) -- Final accumulators and result list
656 mapAccumB f a b [] = (a,b,[])
657 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
659 (a',b'',y) = f a b' x
660 (a'',b',ys) = mapAccumB f a' b xs
663 %************************************************************************
665 \subsection[Utils-comparison]{Comparisons}
667 %************************************************************************
669 See also @tagCmp_@ near the versions-compatibility section.
671 The Ord3 class will be subsumed into Ord in Haskell 1.3.
675 cmp :: a -> a -> TAG_
677 thenCmp :: TAG_ -> TAG_ -> TAG_
678 {-# INLINE thenCmp #-}
679 thenCmp EQ_ any = any
680 thenCmp other any = other
682 cmpList :: (a -> a -> TAG_) -> [a] -> [a] -> TAG_
683 -- `cmpList' uses a user-specified comparer
685 cmpList cmp [] [] = EQ_
686 cmpList cmp [] _ = LT_
687 cmpList cmp _ [] = GT_
688 cmpList cmp (a:as) (b:bs)
689 = case cmp a b of { EQ_ -> cmpList cmp as bs; xxx -> xxx }
693 instance Ord3 a => Ord3 [a] where
697 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
699 instance Ord3 a => Ord3 (Maybe a) where
700 cmp Nothing Nothing = EQ_
701 cmp Nothing (Just y) = LT_
702 cmp (Just x) Nothing = GT_
703 cmp (Just x) (Just y) = x `cmp` y
705 instance Ord3 Int where
706 cmp a b | a < b = LT_
712 cmpString :: String -> String -> TAG_
714 cmpString [] [] = EQ_
715 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
716 else if x < y then LT_
718 cmpString [] ys = LT_
719 cmpString xs [] = GT_
721 cmpString _ _ = panic# "cmpString"
725 #ifdef USE_FAST_STRINGS
726 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
729 = case (_tagCmp x y) of { _LT -> LT_ ; _EQ -> EQ_ ; _GT -> GT_ }
734 #ifndef USE_FAST_STRINGS
735 substr :: FAST_STRING -> Int -> Int -> FAST_STRING
738 = ASSERT (beg >= 0 && beg <= end)
739 take (end - beg + 1) (drop beg str)
743 %************************************************************************
745 \subsection[Utils-pairs]{Pairs}
747 %************************************************************************
749 The following are curried versions of @fst@ and @snd@.
752 cfst :: a -> b -> a -- stranal-sem only (Note)
756 The following provide us higher order functions that, when applied
757 to a function, operate on pairs.
760 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
761 applyToPair (f,g) (x,y) = (f x, g y)
763 applyToFst :: (a -> c) -> (a,b)-> (c,b)
764 applyToFst f (x,y) = (f x,y)
766 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
767 applyToSnd f (x,y) = (x,f y)
769 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
770 foldPair fg ab [] = ab
771 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
772 where (u,v) = foldPair fg ab abs
776 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
777 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
780 %************************************************************************
782 \subsection[Utils-errors]{Error handling}
784 %************************************************************************
787 #if defined(COMPILING_GHC)
788 panic x = error ("panic! (the `impossible' happened):\n\t"
790 ++ "Please report it as a compiler bug "
791 ++ "to glasgow-haskell-bugs@dcs.glasgow.ac.uk.\n\n" )
793 pprPanic heading pretty_msg = panic (heading++(ppShow 80 pretty_msg))
794 pprError heading pretty_msg = error (heading++(ppShow 80 pretty_msg))
795 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
797 -- #-versions because panic can't return an unboxed int, and that's
798 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
799 -- No, man -- Too Beautiful! (Will)
801 panic# :: String -> TAG_
802 panic# s = case (panic s) of () -> EQ_
804 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
806 assertPanic :: String -> Int -> a
807 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
809 #endif {- COMPILING_GHC -}