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_ Ordering
20 # define tagCmp_ compare
21 # define _tagCmp compare
22 # define FAST_STRING String
23 # define ASSERT(x) {-nothing-}
24 # define IF_NOT_GHC(a) a
28 #ifndef __GLASGOW_HASKELL__
37 -- Haskell-version support
38 #ifndef __GLASGOW_HASKELL__
42 -- general list processing
43 IF_NOT_GHC(forall COMMA exists COMMA)
44 zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
46 mapAndUnzip, mapAndUnzip3,
47 nOfThem, lengthExceeds, isSingleton,
49 #if defined(COMPILING_GHC)
57 hasNoDups, equivClasses, runs, removeDups,
60 IF_NOT_GHC(quicksort COMMA stableSortLt COMMA mergesort COMMA)
62 IF_NOT_GHC(mergeSort COMMA) naturalMergeSortLe, -- from Carsten
63 IF_NOT_GHC(naturalMergeSort COMMA mergeSortLe COMMA)
65 -- transitive closures
69 mapAccumL, mapAccumR, mapAccumB,
72 #if defined(COMPILING_GHC)
80 IF_NOT_GHC(cfst COMMA applyToPair COMMA applyToFst COMMA)
81 IF_NOT_GHC(applyToSnd COMMA foldPair COMMA)
85 #if defined(COMPILING_GHC)
86 , panic, panic#, pprPanic, pprPanic#, pprError, pprTrace
88 #endif {- COMPILING_GHC -}
98 %************************************************************************
100 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
102 %************************************************************************
104 This is our own idea:
106 #ifndef __GLASGOW_HASKELL__
107 data TAG_ = LT_ | EQ_ | GT_
109 tagCmp_ :: Ord a => a -> a -> TAG_
110 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
114 %************************************************************************
116 \subsection[Utils-lists]{General list processing}
118 %************************************************************************
120 Quantifiers are not standard in Haskell. The following fill in the gap.
123 forall :: (a -> Bool) -> [a] -> Bool
124 forall pred [] = True
125 forall pred (x:xs) = pred x && forall pred xs
127 exists :: (a -> Bool) -> [a] -> Bool
128 exists pred [] = False
129 exists pred (x:xs) = pred x || exists pred xs
132 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
133 are of equal length. Alastair Reid thinks this should only happen if
134 DEBUGging on; hey, why not?
135 [In the GHC syslib, we want the paranoid behaviour by default --SOF]
138 zipEqual :: String -> [a] -> [b] -> [(a,b)]
139 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
140 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
141 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
143 #if (!defined(DEBUG)) && defined(COMPILING_GHC)
145 zipWithEqual _ = zipWith
146 zipWith3Equal _ = zipWith3
147 zipWith4Equal _ = zipWith4
149 zipEqual msg [] [] = []
150 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
151 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
153 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
154 zipWithEqual msg _ [] [] = []
155 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
157 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
158 = z a b c : zipWith3Equal msg z as bs cs
159 zipWith3Equal msg _ [] [] [] = []
160 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
162 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
163 = z a b c d : zipWith4Equal msg z as bs cs ds
164 zipWith4Equal msg _ [] [] [] [] = []
165 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
170 -- zipLazy is lazy in the second list (observe the ~)
172 zipLazy :: [a] -> [b] -> [(a,b)]
174 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
178 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
180 mapAndUnzip f [] = ([],[])
184 (rs1, rs2) = mapAndUnzip f xs
188 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
190 mapAndUnzip3 f [] = ([],[],[])
191 mapAndUnzip3 f (x:xs)
194 (rs1, rs2, rs3) = mapAndUnzip3 f xs
196 (r1:rs1, r2:rs2, r3:rs3)
200 nOfThem :: Int -> a -> [a]
201 nOfThem = replicate -- deprecated.
203 lengthExceeds :: [a] -> Int -> Bool
205 [] `lengthExceeds` n = 0 > n
206 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
208 isSingleton :: [a] -> Bool
210 isSingleton [x] = True
211 isSingleton _ = False
213 startsWith, endsWith :: String -> String -> Maybe String
215 startsWith [] str = Just str
216 startsWith (c:cs) (s:ss)
217 = if c /= s then Nothing else startsWith cs ss
218 startsWith _ [] = Nothing
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 -> Ordering) -- 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 -> Ordering) -- 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 -> Ordering) -> [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 go done (x:xs) | x `is_in` done = go done xs
594 | otherwise = go (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.
676 cmp :: a -> a -> TAG_
679 thenCmp :: Ordering -> Ordering -> Ordering
680 {-# INLINE thenCmp #-}
682 thenCmp other any = other
684 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
685 -- `cmpList' uses a user-specified comparer
687 cmpList cmp [] [] = EQ
688 cmpList cmp [] _ = LT
689 cmpList cmp _ [] = GT
690 cmpList cmp (a:as) (b:bs)
691 = case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
695 instance Ord3 a => Ord3 [a] where
699 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
701 instance Ord3 a => Ord3 (Maybe a) where
702 cmp Nothing Nothing = EQ_
703 cmp Nothing (Just y) = LT_
704 cmp (Just x) Nothing = GT_
705 cmp (Just x) (Just y) = x `cmp` y
707 instance Ord3 Int where
708 cmp a b | a < b = LT_
714 cmpString :: String -> String -> TAG_
716 cmpString [] [] = EQ_
717 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
718 else if x < y then LT_
720 cmpString [] ys = LT_
721 cmpString xs [] = GT_
724 cmpString _ _ = panic# "cmpString"
726 cmpString _ _ = error "cmpString"
731 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
733 cmpPString x y = compare x y
736 %************************************************************************
738 \subsection[Utils-pairs]{Pairs}
740 %************************************************************************
742 The following are curried versions of @fst@ and @snd@.
745 cfst :: a -> b -> a -- stranal-sem only (Note)
749 The following provide us higher order functions that, when applied
750 to a function, operate on pairs.
753 applyToPair :: ((a -> c),(b -> d)) -> (a,b) -> (c,d)
754 applyToPair (f,g) (x,y) = (f x, g y)
756 applyToFst :: (a -> c) -> (a,b)-> (c,b)
757 applyToFst f (x,y) = (f x,y)
759 applyToSnd :: (b -> d) -> (a,b) -> (a,d)
760 applyToSnd f (x,y) = (x,f y)
762 foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
763 foldPair fg ab [] = ab
764 foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
765 where (u,v) = foldPair fg ab abs
769 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
770 unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
773 %************************************************************************
775 \subsection[Utils-errors]{Error handling}
777 %************************************************************************
780 #if defined(COMPILING_GHC)
781 panic x = error ("panic! (the `impossible' happened):\n\t"
783 ++ "Please report it as a compiler bug "
784 ++ "to glasgow-haskell-bugs@dcs.gla.ac.uk.\n\n" )
786 pprPanic heading pretty_msg = panic (heading++(ppShow 80 pretty_msg))
787 pprError heading pretty_msg = error (heading++(ppShow 80 pretty_msg))
788 #if __GLASGOW_HASKELL__ == 201
789 pprTrace heading pretty_msg = GHCbase.trace (heading++(ppShow 80 pretty_msg))
790 #elsif __GLASGOW_HASKELL__ >= 201
791 pprTrace heading pretty_msg = GHC.trace (heading++(ppShow 80 pretty_msg))
793 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
796 -- #-versions because panic can't return an unboxed int, and that's
797 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
798 -- No, man -- Too Beautiful! (Will)
800 panic# :: String -> TAG_
801 panic# s = case (panic s) of () -> EQ_
803 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
805 assertPanic :: String -> Int -> a
806 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
808 #endif {- COMPILING_GHC -}