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,
48 #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)
73 Ord3(..), thenCmp, cmpList,
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?
144 zipEqual :: String -> [a] -> [b] -> [(a,b)]
145 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
146 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
147 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
151 zipWithEqual _ = zipWith
152 zipWith3Equal _ = zipWith3
153 zipWith4Equal _ = zipWith4
155 zipEqual msg [] [] = []
156 zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
157 zipEqual msg as bs = panic ("zipEqual: unequal lists:"++msg)
159 zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
160 zipWithEqual msg _ [] [] = []
161 zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
163 zipWith3Equal msg z (a:as) (b:bs) (c:cs)
164 = z a b c : zipWith3Equal msg z as bs cs
165 zipWith3Equal msg _ [] [] [] = []
166 zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
168 zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
169 = z a b c d : zipWith4Equal msg z as bs cs ds
170 zipWith4Equal msg _ [] [] [] [] = []
171 zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
176 -- zipLazy is lazy in the second list (observe the ~)
178 zipLazy :: [a] -> [b] -> [(a,b)]
180 zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
184 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
186 mapAndUnzip f [] = ([],[])
190 (rs1, rs2) = mapAndUnzip f xs
194 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
196 mapAndUnzip3 f [] = ([],[],[])
197 mapAndUnzip3 f (x:xs)
200 (rs1, rs2, rs3) = mapAndUnzip3 f xs
202 (r1:rs1, r2:rs2, r3:rs3)
206 nOfThem :: Int -> a -> [a]
207 nOfThem n thing = take n (repeat thing)
209 lengthExceeds :: [a] -> Int -> Bool
211 [] `lengthExceeds` n = 0 > n
212 (x:xs) `lengthExceeds` n = (1 > n) || (xs `lengthExceeds` (n - 1))
214 isSingleton :: [a] -> Bool
216 isSingleton [x] = True
217 isSingleton _ = False
219 startsWith, endsWith :: String -> String -> Maybe String
221 startsWith [] str = Just str
222 startsWith (c:cs) (s:ss)
223 = if c /= s then Nothing else startsWith cs ss
224 startsWith _ [] = Nothing
227 = case (startsWith (reverse cs) (reverse ss)) of
229 Just rs -> Just (reverse rs)
232 Debugging/specialising versions of \tr{elem} and \tr{notElem}
234 #if defined(COMPILING_GHC)
235 isIn, isn'tIn :: (Eq a) => String -> a -> [a] -> Bool
238 isIn msg x ys = elem__ x ys
239 isn'tIn msg x ys = notElem__ x ys
241 --these are here to be SPECIALIZEd (automagically)
243 elem__ x (y:ys) = x==y || elem__ x ys
245 notElem__ x [] = True
246 notElem__ x (y:ys) = x /= y && notElem__ x ys
254 | i _GE_ ILIT(100) = panic ("Over-long elem in: " ++ msg)
255 | otherwise = x == y || elem (i _ADD_ ILIT(1)) x ys
258 = notElem ILIT(0) x ys
260 notElem i x [] = True
262 | i _GE_ ILIT(100) = panic ("Over-long notElem in: " ++ msg)
263 | otherwise = x /= y && notElem (i _ADD_ ILIT(1)) x ys
267 #endif {- COMPILING_GHC -}
270 %************************************************************************
272 \subsection[Utils-assoc]{Association lists}
274 %************************************************************************
276 See also @assocMaybe@ and @mkLookupFun@ in module @Maybes@.
279 assoc :: (Eq a) => String -> [(a, b)] -> a -> b
281 assoc crash_msg lst key
283 then panic ("Failed in assoc: " ++ crash_msg)
285 where res = [ val | (key', val) <- lst, key == key']
288 %************************************************************************
290 \subsection[Utils-dups]{Duplicate-handling}
292 %************************************************************************
295 hasNoDups :: (Eq a) => [a] -> Bool
297 hasNoDups xs = f [] xs
299 f seen_so_far [] = True
300 f seen_so_far (x:xs) = if x `is_elem` seen_so_far then
305 #if defined(COMPILING_GHC)
306 is_elem = isIn "hasNoDups"
313 equivClasses :: (a -> a -> TAG_) -- Comparison
317 equivClasses cmp stuff@[] = []
318 equivClasses cmp stuff@[item] = [stuff]
319 equivClasses cmp items
320 = runs eq (sortLt lt items)
322 eq a b = case cmp a b of { EQ_ -> True; _ -> False }
323 lt a b = case cmp a b of { LT_ -> True; _ -> False }
326 The first cases in @equivClasses@ above are just to cut to the point
329 @runs@ groups a list into a list of lists, each sublist being a run of
330 identical elements of the input list. It is passed a predicate @p@ which
331 tells when two elements are equal.
334 runs :: (a -> a -> Bool) -- Equality
339 runs p (x:xs) = case (span (p x) xs) of
340 (first, rest) -> (x:first) : (runs p rest)
344 removeDups :: (a -> a -> TAG_) -- Comparison function
346 -> ([a], -- List with no duplicates
347 [[a]]) -- List of duplicate groups. One representative from
348 -- each group appears in the first result
350 removeDups cmp [] = ([], [])
351 removeDups cmp [x] = ([x],[])
353 = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
356 collect_dups dups_so_far [x] = (dups_so_far, x)
357 collect_dups dups_so_far dups@(x:xs) = (dups:dups_so_far, x)
360 %************************************************************************
362 \subsection[Utils-sorting]{Sorting}
364 %************************************************************************
366 %************************************************************************
368 \subsubsection[Utils-quicksorting]{Quicksorts}
370 %************************************************************************
373 -- tail-recursive, etc., "quicker sort" [as per Meira thesis]
374 quicksort :: (a -> a -> Bool) -- Less-than predicate
376 -> [a] -- Result list in increasing order
379 quicksort lt [x] = [x]
380 quicksort lt (x:xs) = split x [] [] xs
382 split x lo hi [] = quicksort lt lo ++ (x : quicksort lt hi)
383 split x lo hi (y:ys) | y `lt` x = split x (y:lo) hi ys
384 | True = split x lo (y:hi) ys
387 Quicksort variant from Lennart's Haskell-library contribution. This
388 is a {\em stable} sort.
391 stableSortLt = sortLt -- synonym; when we want to highlight stable-ness
393 sortLt :: (a -> a -> Bool) -- Less-than predicate
395 -> [a] -- Result list
397 sortLt lt l = qsort lt l []
399 -- qsort is stable and does not concatenate.
400 qsort :: (a -> a -> Bool) -- Less-than predicate
401 -> [a] -- xs, Input list
402 -> [a] -- r, Concatenate this list to the sorted input list
403 -> [a] -- Result = sort xs ++ r
407 qsort lt (x:xs) r = qpart lt x xs [] [] r
409 -- qpart partitions and sorts the sublists
410 -- rlt contains things less than x,
411 -- rge contains the ones greater than or equal to x.
412 -- Both have equal elements reversed with respect to the original list.
414 qpart lt x [] rlt rge r =
415 -- rlt and rge are in reverse order and must be sorted with an
416 -- anti-stable sorting
417 rqsort lt rlt (x : rqsort lt rge r)
419 qpart lt x (y:ys) rlt rge r =
422 qpart lt x ys (y:rlt) rge r
425 qpart lt x ys rlt (y:rge) r
427 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
429 rqsort lt [x] r = x:r
430 rqsort lt (x:xs) r = rqpart lt x xs [] [] r
432 rqpart lt x [] rle rgt r =
433 qsort lt rle (x : qsort lt rgt r)
435 rqpart lt x (y:ys) rle rgt r =
438 rqpart lt x ys rle (y:rgt) r
441 rqpart lt x ys (y:rle) rgt r
444 %************************************************************************
446 \subsubsection[Utils-dull-mergesort]{A rather dull mergesort}
448 %************************************************************************
451 mergesort :: (a -> a -> TAG_) -> [a] -> [a]
453 mergesort cmp xs = merge_lists (split_into_runs [] xs)
455 a `le` b = case cmp a b of { LT_ -> True; EQ_ -> True; GT__ -> False }
456 a `ge` b = case cmp a b of { LT_ -> False; EQ_ -> True; GT__ -> True }
458 split_into_runs [] [] = []
459 split_into_runs run [] = [run]
460 split_into_runs [] (x:xs) = split_into_runs [x] xs
461 split_into_runs [r] (x:xs) | x `ge` r = split_into_runs [r,x] xs
462 split_into_runs rl@(r:rs) (x:xs) | x `le` r = split_into_runs (x:rl) xs
463 | True = rl : (split_into_runs [x] xs)
466 merge_lists (x:xs) = merge x (merge_lists xs)
470 merge xl@(x:xs) yl@(y:ys)
472 EQ_ -> x : y : (merge xs ys)
473 LT_ -> x : (merge xs yl)
474 GT__ -> y : (merge xl ys)
477 %************************************************************************
479 \subsubsection[Utils-Carsten-mergesort]{A mergesort from Carsten}
481 %************************************************************************
484 Date: Mon, 3 May 93 20:45:23 +0200
485 From: Carsten Kehler Holst <kehler@cs.chalmers.se>
486 To: partain@dcs.gla.ac.uk
487 Subject: natural merge sort beats quick sort [ and it is prettier ]
489 Here is a piece of Haskell code that I'm rather fond of. See it as an
490 attempt to get rid of the ridiculous quick-sort routine. group is
491 quite useful by itself I think it was John's idea originally though I
492 believe the lazy version is due to me [surprisingly complicated].
493 gamma [used to be called] is called gamma because I got inspired by
494 the Gamma calculus. It is not very close to the calculus but does
495 behave less sequentially than both foldr and foldl. One could imagine
496 a version of gamma that took a unit element as well thereby avoiding
497 the problem with empty lists.
499 I've tried this code against
501 1) insertion sort - as provided by haskell
502 2) the normal implementation of quick sort
503 3) a deforested version of quick sort due to Jan Sparud
504 4) a super-optimized-quick-sort of Lennart's
506 If the list is partially sorted both merge sort and in particular
507 natural merge sort wins. If the list is random [ average length of
508 rising subsequences = approx 2 ] mergesort still wins and natural
509 merge sort is marginally beaten by Lennart's soqs. The space
510 consumption of merge sort is a bit worse than Lennart's quick sort
511 approx a factor of 2. And a lot worse if Sparud's bug-fix [see his
512 fpca article ] isn't used because of group.
519 group :: (a -> a -> Bool) -> [a] -> [[a]]
522 Date: Mon, 12 Feb 1996 15:09:41 +0000
523 From: Andy Gill <andy@dcs.gla.ac.uk>
525 Here is a `better' definition of group.
528 group p (x:xs) = group' xs x x (x :)
530 group' [] _ _ s = [s []]
531 group' (x:xs) x_min x_max s
532 | not (x `p` x_max) = group' xs x_min x (s . (x :))
533 | x `p` x_min = group' xs x x_max ((x :) . s)
534 | otherwise = s [] : group' xs x x (x :)
536 -- This one works forwards *and* backwards, as well as also being
537 -- faster that the one in Util.lhs.
542 let ((h1:t1):tt1) = group p xs
543 (t,tt) = if null xs then ([],[]) else
544 if x `p` h1 then (h1:t1,tt1) else
549 generalMerge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
550 generalMerge p xs [] = xs
551 generalMerge p [] ys = ys
552 generalMerge p (x:xs) (y:ys) | x `p` y = x : generalMerge p xs (y:ys)
553 | otherwise = y : generalMerge p (x:xs) ys
555 -- gamma is now called balancedFold
557 balancedFold :: (a -> a -> a) -> [a] -> a
558 balancedFold f [] = error "can't reduce an empty list using balancedFold"
559 balancedFold f [x] = x
560 balancedFold f l = balancedFold f (balancedFold' f l)
562 balancedFold' :: (a -> a -> a) -> [a] -> [a]
563 balancedFold' f (x:y:xs) = f x y : balancedFold' f xs
564 balancedFold' f xs = xs
566 generalMergeSort p [] = []
567 generalMergeSort p xs = (balancedFold (generalMerge p) . map (: [])) xs
569 generalNaturalMergeSort p [] = []
570 generalNaturalMergeSort p xs = (balancedFold (generalMerge p) . group p) xs
572 mergeSort, naturalMergeSort :: Ord a => [a] -> [a]
574 mergeSort = generalMergeSort (<=)
575 naturalMergeSort = generalNaturalMergeSort (<=)
577 mergeSortLe le = generalMergeSort le
578 naturalMergeSortLe le = generalNaturalMergeSort le
581 %************************************************************************
583 \subsection[Utils-transitive-closure]{Transitive closure}
585 %************************************************************************
587 This algorithm for transitive closure is straightforward, albeit quadratic.
590 transitiveClosure :: (a -> [a]) -- Successor function
591 -> (a -> a -> Bool) -- Equality predicate
593 -> [a] -- The transitive closure
595 transitiveClosure succ eq xs
599 go done (x:xs) | x `is_in` done = go done xs
600 | otherwise = go (x:done) (succ x ++ xs)
603 x `is_in` (y:ys) | eq x y = True
604 | otherwise = x `is_in` ys
607 %************************************************************************
609 \subsection[Utils-accum]{Accumulating}
611 %************************************************************************
613 @mapAccumL@ behaves like a combination
614 of @map@ and @foldl@;
615 it applies a function to each element of a list, passing an accumulating
616 parameter from left to right, and returning a final value of this
617 accumulator together with the new list.
620 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
621 -- and accumulator, returning new
622 -- accumulator and elt of result list
623 -> acc -- Initial accumulator
625 -> (acc, [y]) -- Final accumulator and result list
627 mapAccumL f b [] = (b, [])
628 mapAccumL f b (x:xs) = (b'', x':xs') where
630 (b'', xs') = mapAccumL f b' xs
633 @mapAccumR@ does the same, but working from right to left instead. Its type is
634 the same as @mapAccumL@, though.
637 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
638 -- and accumulator, returning new
639 -- accumulator and elt of result list
640 -> acc -- Initial accumulator
642 -> (acc, [y]) -- Final accumulator and result list
644 mapAccumR f b [] = (b, [])
645 mapAccumR f b (x:xs) = (b'', x':xs') where
647 (b', xs') = mapAccumR f b xs
650 Here is the bi-directional version, that works from both left and right.
653 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
654 -- Function of elt of input list
655 -- and accumulator, returning new
656 -- accumulator and elt of result list
657 -> accl -- Initial accumulator from left
658 -> accr -- Initial accumulator from right
660 -> (accl, accr, [y]) -- Final accumulators and result list
662 mapAccumB f a b [] = (a,b,[])
663 mapAccumB f a b (x:xs) = (a'',b'',y:ys)
665 (a',b'',y) = f a b' x
666 (a'',b',ys) = mapAccumB f a' b xs
669 %************************************************************************
671 \subsection[Utils-comparison]{Comparisons}
673 %************************************************************************
675 See also @tagCmp_@ near the versions-compatibility section.
677 The Ord3 class will be subsumed into Ord in Haskell 1.3.
681 cmp :: a -> a -> TAG_
683 thenCmp :: TAG_ -> TAG_ -> TAG_
684 {-# INLINE thenCmp #-}
685 thenCmp EQ_ any = any
686 thenCmp other any = other
688 cmpList :: (a -> a -> TAG_) -> [a] -> [a] -> TAG_
689 -- `cmpList' uses a user-specified comparer
691 cmpList cmp [] [] = EQ_
692 cmpList cmp [] _ = LT_
693 cmpList cmp _ [] = GT_
694 cmpList cmp (a:as) (b:bs)
695 = case cmp a b of { EQ_ -> cmpList cmp as bs; xxx -> xxx }
699 instance Ord3 a => Ord3 [a] where
703 cmp (x:xs) (y:ys) = (x `cmp` y) `thenCmp` (xs `cmp` ys)
705 instance Ord3 a => Ord3 (Maybe a) where
706 cmp Nothing Nothing = EQ_
707 cmp Nothing (Just y) = LT_
708 cmp (Just x) Nothing = GT_
709 cmp (Just x) (Just y) = x `cmp` y
711 instance Ord3 Int where
712 cmp a b | a < b = LT_
718 cmpString :: String -> String -> TAG_
720 cmpString [] [] = EQ_
721 cmpString (x:xs) (y:ys) = if x == y then cmpString xs ys
722 else if x < y then LT_
724 cmpString [] ys = LT_
725 cmpString xs [] = GT_
728 cmpString _ _ = panic# "cmpString"
730 cmpString _ _ = error "cmpString"
735 cmpPString :: FAST_STRING -> FAST_STRING -> TAG_
738 = case (_tagCmp x y) of { _LT -> LT_ ; _EQ -> EQ_ ; _GT -> GT_ }
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.gla.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 #if __GLASGOW_HASKELL__ >= 200
794 pprTrace heading pretty_msg = GHCbase.trace (heading++(ppShow 80 pretty_msg))
796 pprTrace heading pretty_msg = trace (heading++(ppShow 80 pretty_msg))
799 -- #-versions because panic can't return an unboxed int, and that's
800 -- what TAG_ is with GHC at the moment. Ugh. (Simon)
801 -- No, man -- Too Beautiful! (Will)
803 panic# :: String -> TAG_
804 panic# s = case (panic s) of () -> EQ_
806 pprPanic# heading pretty_msg = panic# (heading++(ppShow 80 pretty_msg))
808 assertPanic :: String -> Int -> a
809 assertPanic file line = panic ("ASSERT failed! file "++file++", line "++show line)
811 #endif {- COMPILING_GHC -}