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 -}
92 #if defined(COMPILING_GHC)
94 CHK_Ubiq() -- debugging consistency check
95 IMPORT_1_3(List(zipWith4))
105 %************************************************************************
107 \subsection[Utils-version-support]{Functions to help pre-1.2 versions of (non-Glasgow) Haskell}
109 %************************************************************************
111 This is our own idea:
113 #ifndef __GLASGOW_HASKELL__
114 data TAG_ = LT_ | EQ_ | GT_
116 tagCmp_ :: Ord a => a -> a -> TAG_
117 tagCmp_ a b = if a == b then EQ_ else if a < b then LT_ else GT_
121 %************************************************************************
123 \subsection[Utils-lists]{General list processing}
125 %************************************************************************
127 Quantifiers are not standard in Haskell. The following fill in the gap.
130 forall :: (a -> Bool) -> [a] -> Bool
131 forall pred [] = True
132 forall pred (x:xs) = pred x && forall pred xs
134 exists :: (a -> Bool) -> [a] -> Bool
135 exists pred [] = False
136 exists pred (x:xs) = pred x || exists pred xs
139 A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
140 are of equal length. Alastair Reid thinks this should only happen if
141 DEBUGging on; hey, why not?
142 [In the GHC syslib, we want the paranoid behaviour by default --SOF]
145 zipEqual :: String -> [a] -> [b] -> [(a,b)]
146 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
147 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
148 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
150 #if (!defined(DEBUG)) && defined(COMPILING_GHC)
152 zipWithEqual _ = zipWith
153 zipWith3Equal _ = zipWith3
154 zipWith4Equal _ = zipWith4
156 zipEqual msg [] [] = []
157 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
158 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
160 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
161 zipWithEqual msg _ [] [] = []
162 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
164 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
165 = z a b c : zipWith3Equal msg z as bs cs
166 zipWith3Equal msg _ [] [] [] = []
167 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
169 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
170 = z a b c d : zipWith4Equal msg z as bs cs ds
171 zipWith4Equal msg _ [] [] [] [] = []
172 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
177 -- zipLazy is lazy in the second list (observe the ~)
179 zipLazy :: [a] -> [b] -> [(a,b)]
181 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
185 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
187 mapAndUnzip f [] = ([],[])
191 (rs1, rs2) = mapAndUnzip f xs
195 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
197 mapAndUnzip3 f [] = ([],[],[])
198 mapAndUnzip3 f (x:xs)
201 (rs1, rs2, rs3) = mapAndUnzip3 f xs
203 (r1:rs1, r2:rs2, r3:rs3)
207 nOfThem :: Int -> a -> [a]
208 nOfThem = replicate -- deprecated.
210 lengthExceeds :: [a] -> Int -> Bool
212 [] `lengthExceeds` n = 0 > n
213 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
215 isSingleton :: [a] -> Bool
217 isSingleton [x] = True
218 isSingleton _ = False
220 startsWith, endsWith :: String -> String -> Maybe String
222 startsWith [] str = Just str
223 startsWith (c:cs) (s:ss)
224 = if c /= s then Nothing else startsWith cs ss
225 startsWith _ [] = Nothing
228 = case (startsWith (reverse cs) (reverse ss)) of
230 Just rs -> Just (reverse rs)
233 Debugging/specialising versions of \tr{elem} and \tr{notElem}
235 #if defined(COMPILING_GHC)
236 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
239 isIn msg x ys = elem__ x ys
240 isn'tIn msg x ys = notElem__ x ys
242 --these are here to be SPECIALIZEd (automagically)
244 elem__ x (y:ys) = x==y || elem__ x ys
246 notElem__ x [] = True
247 notElem__ x (y:ys) = x /= y && notElem__ x ys
255 | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
256 | otherwise = x == y || elem (i _ADD_ ILIT(1)) x ys
259 = notElem ILIT(0) x ys
261 notElem i x [] = True
263 | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
264 | otherwise = x /= y && notElem (i _ADD_ ILIT(1)) x ys
268 #endif {- COMPILING_GHC -}
271 %************************************************************************
273 \subsection[Utils-assoc]{Association lists}
275 %************************************************************************
277 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
280 assoc :: (Eq a) => String -> [(a, b)] -> a -> b
282 assoc crash_msg lst key
284 then panic ("Failed in assoc: " ++ crash_msg)
286 where res = [ val | (key', val) <- lst, key == key']
289 %************************************************************************
291 \subsection[Utils-dups]{Duplicate-handling}
293 %************************************************************************
296 hasNoDups :: (Eq a) => [a] -> Bool
298 hasNoDups xs = f [] xs
300 f seen_so_far [] = True
301 f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
306 #if defined(COMPILING_GHC)
307 is_elem = isIn "hasNoDups"
314 equivClasses :: (a -> a -> Ordering) -- Comparison
318 equivClasses cmp stuff@[] = []
319 equivClasses cmp stuff@[item] = [stuff]
320 equivClasses cmp items
321 = runs eq (sortLt lt items)
323 eq a b = case cmp a b of { EQ -> True; _ -> False }
324 lt a b = case cmp a b of { LT -> True; _ -> False }
327 The first cases in @equivClasses@ above are just to cut to the point
330 @runs@ groups a list into a list of lists, each sublist being a run of
331 identical elements of the input list. It is passed a predicate @p@ which
332 tells when two elements are equal.
335 runs :: (a -> a -> Bool) -- Equality
340 runs p (x:xs) = case (span (p x) xs) of
341 (first, rest) -> (x:first) : (runs p rest)
345 removeDups :: (a -> a -> Ordering) -- Comparison function
347 -> ([a], -- List with no duplicates
348 [[a]]) -- List of duplicate groups. One representative from
349 -- each group appears in the first result
351 removeDups cmp [] = ([], [])
352 removeDups cmp [x] = ([x],[])
354 = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
357 collect_dups dups_so_far [x] = (dups_so_far, x)
358 collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
361 %************************************************************************
363 \subsection[Utils-sorting]{Sorting}
365 %************************************************************************
367 %************************************************************************
369 \subsubsection[Utils-quicksorting]{Quicksorts}
371 %************************************************************************
374 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
375 quicksort :: (a -> a -> Bool) -- Less-than predicate
377 -> [a] -- Result list in increasing order
380 quicksort lt [x] = [x]
381 quicksort lt (x:xs) = split x [] [] xs
383 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
384 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
385 | True = split x lo (y:hi) ys
388 Quicksort variant from Lennart's Haskell-library contribution. This
389 is a {\em stable} sort.
392 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
394 sortLt :: (a -> a -> Bool) -- Less-than predicate
396 -> [a] -- Result list
398 sortLt lt l = qsort lt l []
400 -- qsort is stable and does not concatenate.
401 qsort :: (a -> a -> Bool) -- Less-than predicate
402 -> [a] -- xs, Input list
403 -> [a] -- r, Concatenate this list to the sorted input list
404 -> [a] -- Result = sort xs ++ r
408 qsort lt (x:xs) r = qpart lt x xs [] [] r
410 -- qpart partitions and sorts the sublists
411 -- rlt contains things less than x,
412 -- rge contains the ones greater than or equal to x.
413 -- Both have equal elements reversed with respect to the original list.
415 qpart lt x [] rlt rge r =
416 -- rlt and rge are in reverse order and must be sorted with an
417 -- anti-stable sorting
418 rqsort lt rlt (x : rqsort lt rge r)
420 qpart lt x (y:ys) rlt rge r =
423 qpart lt x ys (y:rlt) rge r
426 qpart lt x ys rlt (y:rge) r
428 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
430 rqsort lt [x] r = x:r
431 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
433 rqpart lt x [] rle rgt r =
434 qsort lt rle (x : qsort lt rgt r)
436 rqpart lt x (y:ys) rle rgt r =
439 rqpart lt x ys rle (y:rgt) r
442 rqpart lt x ys (y:rle) rgt r
445 %************************************************************************
447 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
449 %************************************************************************
452 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
454 mergesort cmp xs = merge_lists (split_into_runs [] xs)
456 a `le` b = case cmp a b of { LT_ -> True; EQ_ -> True; GT__ -> False }
457 a `ge` b = case cmp a b of { LT_ -> False; EQ_ -> True; GT__ -> True }
459 split_into_runs [] [] = []
460 split_into_runs run [] = [run]
461 split_into_runs [] (x:xs) = split_into_runs [x] xs
462 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
463 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
464 | True = rl : (split_into_runs [x] xs)
467 merge_lists (x:xs) = merge x (merge_lists xs)
471 merge xl@(x:xs) yl@(y:ys)
473 EQ_ -> x : y : (merge xs ys)
474 LT_ -> x : (merge xs yl)
475 GT__ -> y : (merge xl ys)
478 %************************************************************************
480 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
482 %************************************************************************
485 Date: Mon, 3 May 93 20:45:23 +0200
486 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
487 To: partain@dcs.gla.ac.uk
488 Subject: natural merge sort beats quick sort [ and it is prettier ]
490 Here is a piece of Haskell code that I'm rather fond of. See it as an
491 attempt to get rid of the ridiculous quick-sort routine. group is
492 quite useful by itself I think it was John's idea originally though I
493 believe the lazy version is due to me [surprisingly complicated].
494 gamma [used to be called] is called gamma because I got inspired by
495 the Gamma calculus. It is not very close to the calculus but does
496 behave less sequentially than both foldr and foldl. One could imagine
497 a version of gamma that took a unit element as well thereby avoiding
498 the problem with empty lists.
500 I've tried this code against
502 1) insertion sort - as provided by haskell
503 2) the normal implementation of quick sort
504 3) a deforested version of quick sort due to Jan Sparud
505 4) a super-optimized-quick-sort of Lennart's
507 If the list is partially sorted both merge sort and in particular
508 natural merge sort wins. If the list is random [ average length of
509 rising subsequences = approx 2 ] mergesort still wins and natural
510 merge sort is marginally beaten by Lennart's soqs. The space
511 consumption of merge sort is a bit worse than Lennart's quick sort
512 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
513 fpca article ] isn't used because of group.
520 group :: (a -> a -> Bool) -> [a] -> [[a]]
523 Date: Mon, 12 Feb 1996 15:09:41 +0000
524 From: Andy Gill <andy@dcs.gla.ac.uk>
526 Here is a `better' definition of group.
529 group p (x:xs) = group' xs x x (x :)
531 group' [] _ _ s = [s []]
532 group' (x:xs) x_min x_max s
533 | not (x `p` x_max) = group' xs x_min x (s . (x :))
534 | x `p` x_min = group' xs x x_max ((x :) . s)
535 | otherwise = s [] : group' xs x x (x :)
537 -- This one works forwards *and* backwards, as well as also being
538 -- faster that the one in Util.lhs.
543 let ((h1:t1):tt1) = group p xs
544 (t,tt) = if null xs then ([],[]) else
545 if x `p` h1 then (h1:t1,tt1) else
550 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
551 generalMerge p xs [] = xs
552 generalMerge p [] ys = ys
553 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
554 | otherwise = y : generalMerge p (x:xs) ys
556 -- gamma is now called balancedFold
558 balancedFold :: (a -> a -> a) -> [a] -> a
559 balancedFold f [] = error "can't reduce an empty list using balancedFold"
560 balancedFold f [x] = x
561 balancedFold f l = balancedFold f (balancedFold' f l)
563 balancedFold' :: (a -> a -> a) -> [a] -> [a]
564 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
565 balancedFold' f xs = xs
567 generalMergeSort p [] = []
568 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
570 generalNaturalMergeSort p [] = []
571 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
573 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
575 mergeSort = generalMergeSort (<=)
576 naturalMergeSort = generalNaturalMergeSort (<=)
578 mergeSortLe le = generalMergeSort le
579 naturalMergeSortLe le = generalNaturalMergeSort le
582 %************************************************************************
584 \subsection[Utils-transitive-closure]{Transitive closure}
586 %************************************************************************
588 This algorithm for transitive closure is straightforward, albeit quadratic.
591 transitiveClosure :: (a -> [a]) -- Successor function
592 -> (a -> a -> Bool) -- Equality predicate
594 -> [a] -- The transitive closure
596 transitiveClosure succ eq xs
600 go done (x:xs) | x `is_in` done = go done xs
601 | otherwise = go (x:done) (succ x ++ xs)
604 x `is_in` (y:ys) | eq x y = True
605 | otherwise = x `is_in` ys
608 %************************************************************************
610 \subsection[Utils-accum]{Accumulating}
612 %************************************************************************
614 @mapAccumL@ behaves like a combination
615 of @map@ and @foldl@;
616 it applies a function to each element of a list, passing an accumulating
617 parameter from left to right, and returning a final value of this
618 accumulator together with the new list.
621 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
622 -- and accumulator, returning new
623 -- accumulator and elt of result list
624 -> acc -- Initial accumulator
626 -> (acc, [y]) -- Final accumulator and result list
628 mapAccumL f b [] = (b, [])
629 mapAccumL f b (x:xs) = (b'', x':xs') where
631 (b'', xs') = mapAccumL f b' xs
634 @mapAccumR@ does the same, but working from right to left instead. Its type is
635 the same as @mapAccumL@, though.
638 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
639 -- and accumulator, returning new
640 -- accumulator and elt of result list
641 -> acc -- Initial accumulator
643 -> (acc, [y]) -- Final accumulator and result list
645 mapAccumR f b [] = (b, [])
646 mapAccumR f b (x:xs) = (b'', x':xs') where
648 (b', xs') = mapAccumR f b xs
651 Here is the bi-directional version, that works from both left and right.
654 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
655 -- Function of elt of input list
656 -- and accumulator, returning new
657 -- accumulator and elt of result list
658 -> accl -- Initial accumulator from left
659 -> accr -- Initial accumulator from right
661 -> (accl, accr, [y]) -- Final accumulators and result list
663 mapAccumB f a b [] = (a,b,[])
664 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
666 (a',b'',y) = f a b' x
667 (a'',b',ys) = mapAccumB f a' b xs
670 %************************************************************************
672 \subsection[Utils-comparison]{Comparisons}
674 %************************************************************************
676 See also @tagCmp_@ near the versions-compatibility section.
678 The Ord3 class will be subsumed into Ord in Haskell 1.3.
683 cmp :: a -> a -> TAG_
686 thenCmp :: Ordering -> Ordering -> Ordering
687 {-# INLINE thenCmp #-}
689 thenCmp other any = other
691 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
692 -- `cmpList' uses a user-specified comparer
694 cmpList cmp [] [] = EQ
695 cmpList cmp [] _ = LT
696 cmpList cmp _ [] = GT
697 cmpList cmp (a:as) (b:bs)
698 = case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
702 instance Ord3 a => Ord3 [a] where
706 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
708 instance Ord3 a => Ord3 (Maybe a) where
709 cmp Nothing Nothing = EQ_
710 cmp Nothing (Just y) = LT_
711 cmp (Just x) Nothing = GT_
712 cmp (Just x) (Just y) = x `cmp` y
714 instance Ord3 Int where
715 cmp a b | a < b = LT_
721 cmpString :: String -> String -> TAG_
723 cmpString [] [] = EQ_
724 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
725 else if x < y then LT_
727 cmpString [] ys = LT_
728 cmpString xs [] = GT_
731 cmpString _ _ = panic# "cmpString"
733 cmpString _ _ = error "cmpString"
738 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
740 cmpPString x y = compare x y
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.gla.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 #if __GLASGOW_HASKELL__ == 201
796 pprTrace heading pretty_msg = GHCbase.trace (heading++(ppShow 80 pretty_msg))
797 #elsif __GLASGOW_HASKELL__ >= 201
798 pprTrace heading pretty_msg = GHC.trace (heading++(ppShow 80 pretty_msg))
800 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
803 -- #-versions because panic can't return an unboxed int, and that's
804 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
805 -- No, man -- Too Beautiful! (Will)
807 panic# :: String -> TAG_
808 panic# s = case (panic s) of () -> EQ_
810 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
812 assertPanic :: String -> Int -> a
813 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
815 #endif {- COMPILING_GHC -}