1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
10 -- Portability : portable
12 -- Operations on lists.
14 -----------------------------------------------------------------------------
25 (++) -- :: [a] -> [a] -> [a]
28 , tail -- :: [a] -> [a]
29 , init -- :: [a] -> [a]
30 , null -- :: [a] -> Bool
31 , length -- :: [a] -> Int
33 -- * List transformations
34 , map -- :: (a -> b) -> [a] -> [b]
35 , reverse -- :: [a] -> [a]
37 , intersperse -- :: a -> [a] -> [a]
38 , transpose -- :: [[a]] -> [[a]]
40 -- * Reducing lists (folds)
42 , foldl -- :: (a -> b -> a) -> a -> [b] -> a
43 , foldl' -- :: (a -> b -> a) -> a -> [b] -> a
44 , foldl1 -- :: (a -> a -> a) -> [a] -> a
45 , foldl1' -- :: (a -> a -> a) -> [a] -> a
46 , foldr -- :: (a -> b -> b) -> b -> [a] -> b
47 , foldr1 -- :: (a -> a -> a) -> [a] -> a
51 , concat -- :: [[a]] -> [a]
52 , concatMap -- :: (a -> [b]) -> [a] -> [b]
53 , and -- :: [Bool] -> Bool
54 , or -- :: [Bool] -> Bool
55 , any -- :: (a -> Bool) -> [a] -> Bool
56 , all -- :: (a -> Bool) -> [a] -> Bool
57 , sum -- :: (Num a) => [a] -> a
58 , product -- :: (Num a) => [a] -> a
59 , maximum -- :: (Ord a) => [a] -> a
60 , minimum -- :: (Ord a) => [a] -> a
65 , scanl -- :: (a -> b -> a) -> a -> [b] -> [a]
66 , scanl1 -- :: (a -> a -> a) -> [a] -> [a]
67 , scanr -- :: (a -> b -> b) -> b -> [a] -> [b]
68 , scanr1 -- :: (a -> a -> a) -> [a] -> [a]
70 -- ** Accumulating maps
71 , mapAccumL -- :: (a -> b -> (a,c)) -> a -> [b] -> (a,[c])
72 , mapAccumR -- :: (a -> b -> (a,c)) -> a -> [b] -> (a,[c])
75 , iterate -- :: (a -> a) -> a -> [a]
76 , repeat -- :: a -> [a]
77 , replicate -- :: Int -> a -> [a]
78 , cycle -- :: [a] -> [a]
81 , unfoldr -- :: (b -> Maybe (a, b)) -> b -> [a]
85 -- ** Extracting sublists
86 , take -- :: Int -> [a] -> [a]
87 , drop -- :: Int -> [a] -> [a]
88 , splitAt -- :: Int -> [a] -> ([a], [a])
90 , takeWhile -- :: (a -> Bool) -> [a] -> [a]
91 , dropWhile -- :: (a -> Bool) -> [a] -> [a]
92 , span -- :: (a -> Bool) -> [a] -> ([a], [a])
93 , break -- :: (a -> Bool) -> [a] -> ([a], [a])
95 , group -- :: Eq a => [a] -> [[a]]
97 , inits -- :: [a] -> [[a]]
98 , tails -- :: [a] -> [[a]]
101 , isPrefixOf -- :: (Eq a) => [a] -> [a] -> Bool
102 , isSuffixOf -- :: (Eq a) => [a] -> [a] -> Bool
106 -- ** Searching by equality
107 , elem -- :: a -> [a] -> Bool
108 , notElem -- :: a -> [a] -> Bool
109 , lookup -- :: (Eq a) => a -> [(a,b)] -> Maybe b
111 -- ** Searching with a predicate
112 , find -- :: (a -> Bool) -> [a] -> Maybe a
113 , filter -- :: (a -> Bool) -> [a] -> [a]
114 , partition -- :: (a -> Bool) -> [a] -> ([a], [a])
117 -- | These functions treat a list @xs@ as a indexed collection,
118 -- with indices ranging from 0 to @'length' xs - 1@.
120 , (!!) -- :: [a] -> Int -> a
122 , elemIndex -- :: (Eq a) => a -> [a] -> Maybe Int
123 , elemIndices -- :: (Eq a) => a -> [a] -> [Int]
125 , findIndex -- :: (a -> Bool) -> [a] -> Maybe Int
126 , findIndices -- :: (a -> Bool) -> [a] -> [Int]
128 -- * Zipping and unzipping lists
130 , zip -- :: [a] -> [b] -> [(a,b)]
132 , zip4, zip5, zip6, zip7
134 , zipWith -- :: (a -> b -> c) -> [a] -> [b] -> [c]
136 , zipWith4, zipWith5, zipWith6, zipWith7
138 , unzip -- :: [(a,b)] -> ([a],[b])
140 , unzip4, unzip5, unzip6, unzip7
144 -- ** Functions on strings
145 , lines -- :: String -> [String]
146 , words -- :: String -> [String]
147 , unlines -- :: [String] -> String
148 , unwords -- :: [String] -> String
150 -- ** \"Set\" operations
152 , nub -- :: (Eq a) => [a] -> [a]
154 , delete -- :: (Eq a) => a -> [a] -> [a]
155 , (\\) -- :: (Eq a) => [a] -> [a] -> [a]
157 , union -- :: (Eq a) => [a] -> [a] -> [a]
158 , intersect -- :: (Eq a) => [a] -> [a] -> [a]
161 , sort -- :: (Ord a) => [a] -> [a]
162 , insert -- :: (Ord a) => a -> [a] -> [a]
164 -- * Generalized functions
166 -- ** The \"@By@\" operations
167 -- | By convention, overloaded functions have a non-overloaded
168 -- counterpart whose name is suffixed with \`@By@\'.
170 -- *** User-supplied equality (replacing an @Eq@ context)
171 -- | The predicate is assumed to define an equivalence.
172 , nubBy -- :: (a -> a -> Bool) -> [a] -> [a]
173 , deleteBy -- :: (a -> a -> Bool) -> a -> [a] -> [a]
174 , deleteFirstsBy -- :: (a -> a -> Bool) -> [a] -> [a] -> [a]
175 , unionBy -- :: (a -> a -> Bool) -> [a] -> [a] -> [a]
176 , intersectBy -- :: (a -> a -> Bool) -> [a] -> [a] -> [a]
177 , groupBy -- :: (a -> a -> Bool) -> [a] -> [[a]]
179 -- *** User-supplied comparison (replacing an @Ord@ context)
180 -- | The function is assumed to define a total ordering.
181 , sortBy -- :: (a -> a -> Ordering) -> [a] -> [a]
182 , insertBy -- :: (a -> a -> Ordering) -> a -> [a] -> [a]
183 , maximumBy -- :: (a -> a -> Ordering) -> [a] -> a
184 , minimumBy -- :: (a -> a -> Ordering) -> [a] -> a
186 -- ** The \"@generic@\" operations
187 -- | The prefix \`@generic@\' indicates an overloaded function that
188 -- is a generalized version of a "Prelude" function.
190 , genericLength -- :: (Integral a) => [b] -> a
191 , genericTake -- :: (Integral a) => a -> [b] -> [b]
192 , genericDrop -- :: (Integral a) => a -> [b] -> [b]
193 , genericSplitAt -- :: (Integral a) => a -> [b] -> ([b], [b])
194 , genericIndex -- :: (Integral a) => [b] -> a -> b
195 , genericReplicate -- :: (Integral a) => a -> b -> [b]
200 import Prelude hiding (Maybe(..))
204 import Data.Char ( isSpace )
206 #ifdef __GLASGOW_HASKELL__
213 infix 5 \\ -- comment to fool cpp
215 -- -----------------------------------------------------------------------------
218 -- | The 'elemIndex' function returns the index of the first element
219 -- in the given list which is equal (by '==') to the query element,
220 -- or 'Nothing' if there is no such element.
221 elemIndex :: Eq a => a -> [a] -> Maybe Int
222 elemIndex x = findIndex (x==)
224 -- | The 'elemIndices' function extends 'elemIndex', by returning the
225 -- indices of all elements equal to the query element, in ascending order.
226 elemIndices :: Eq a => a -> [a] -> [Int]
227 elemIndices x = findIndices (x==)
229 -- | The 'find' function takes a predicate and a list and returns the
230 -- first element in the list matching the predicate, or 'Nothing' if
231 -- there is no such element.
232 find :: (a -> Bool) -> [a] -> Maybe a
233 find p = listToMaybe . filter p
235 -- | The 'findIndex' function takes a predicate and a list and returns
236 -- the index of the first element in the list satisfying the predicate,
237 -- or 'Nothing' if there is no such element.
238 findIndex :: (a -> Bool) -> [a] -> Maybe Int
239 findIndex p = listToMaybe . findIndices p
241 -- | The 'findIndices' function extends 'findIndex', by returning the
242 -- indices of all elements satisfying the predicate, in ascending order.
243 findIndices :: (a -> Bool) -> [a] -> [Int]
245 #if defined(USE_REPORT_PRELUDE) || !defined(__GLASGOW_HASKELL__)
246 findIndices p xs = [ i | (x,i) <- zip xs [0..], p x]
248 -- Efficient definition
249 findIndices p ls = loop 0# ls
252 loop n (x:xs) | p x = I# n : loop (n +# 1#) xs
253 | otherwise = loop (n +# 1#) xs
254 #endif /* USE_REPORT_PRELUDE */
256 -- | The 'isPrefixOf' function takes two lists and returns 'True'
257 -- iff the first list is a prefix of the second.
258 isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
259 isPrefixOf [] _ = True
260 isPrefixOf _ [] = False
261 isPrefixOf (x:xs) (y:ys)= x == y && isPrefixOf xs ys
263 -- | The 'isSuffixOf' function takes two lists and returns 'True'
264 -- iff the first list is a suffix of the second.
265 -- Both lists must be finite.
266 isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
267 isSuffixOf x y = reverse x `isPrefixOf` reverse y
269 -- | The 'nub' function removes duplicate elements from a list.
270 -- In particular, it keeps only the first occurrence of each element.
271 -- (The name 'nub' means \`essence\'.)
272 -- It is a special case of 'nubBy', which allows the programmer to supply
273 -- their own equality test.
274 nub :: (Eq a) => [a] -> [a]
275 #ifdef USE_REPORT_PRELUDE
279 nub l = nub' l [] -- '
283 | x `elem` ls = nub' xs ls -- '
284 | otherwise = x : nub' xs (x:ls) -- '
287 -- | The 'nubBy' function behaves just like 'nub', except it uses a
288 -- user-supplied equality predicate instead of the overloaded '=='
290 nubBy :: (a -> a -> Bool) -> [a] -> [a]
291 #ifdef USE_REPORT_PRELUDE
293 nubBy eq (x:xs) = x : nubBy eq (filter (\ y -> not (eq x y)) xs)
295 nubBy eq l = nubBy' l []
299 | elem_by eq y xs = nubBy' ys xs
300 | otherwise = y : nubBy' ys (y:xs)
303 -- Note that we keep the call to `eq` with arguments in the
304 -- same order as in the reference implementation
305 -- 'xs' is the list of things we've seen so far,
306 -- 'y' is the potential new element
307 elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool
308 elem_by _ _ [] = False
309 elem_by eq y (x:xs) = x `eq` y || elem_by eq y xs
313 -- | 'delete' @x@ removes the first occurrence of @x@ from its list argument.
316 -- > delete 'a' "banana" == "bnana"
318 -- It is a special case of 'deleteBy', which allows the programmer to
319 -- supply their own equality test.
321 delete :: (Eq a) => a -> [a] -> [a]
322 delete = deleteBy (==)
324 -- | The 'deleteBy' function behaves like 'delete', but takes a
325 -- user-supplied equality predicate.
326 deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
328 deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
330 -- | The '\\' function is list difference ((non-associative).
331 -- In the result of @xs@ '\\' @ys@, the first occurrence of each element of
332 -- @ys@ in turn (if any) has been removed from @xs@. Thus
334 -- > (xs ++ ys) \\ xs == ys.
336 -- It is a special case of 'deleteFirstsBy', which allows the programmer
337 -- to supply their own equality test.
339 (\\) :: (Eq a) => [a] -> [a] -> [a]
340 (\\) = foldl (flip delete)
342 -- | The 'union' function returns the list union of the two lists.
345 -- > "dog" `union` "cow" == "dogcw"
347 -- Duplicates, and elements of the first list, are removed from the
348 -- the second list, but if the first list contains duplicates, so will
350 -- It is a special case of 'unionBy', which allows the programmer to supply
351 -- their own equality test.
353 union :: (Eq a) => [a] -> [a] -> [a]
356 -- | The 'unionBy' function is the non-overloaded version of 'union'.
357 unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
358 unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs
360 -- | The 'intersect' function takes the list intersection of two lists.
363 -- > [1,2,3,4] `intersect` [2,4,6,8] == [2,4]
365 -- If the first list contains duplicates, so will the result.
366 -- It is a special case of 'intersectBy', which allows the programmer to
367 -- supply their own equality test.
369 intersect :: (Eq a) => [a] -> [a] -> [a]
370 intersect = intersectBy (==)
372 -- | The 'intersectBy' function is the non-overloaded version of 'intersect'.
373 intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
374 intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
376 -- | The 'intersperse' function takes an element and a list and
377 -- \`intersperses\' that element between the elements of the list.
380 -- > intersperse ',' "abcde" == "a,b,c,d,e"
382 intersperse :: a -> [a] -> [a]
383 intersperse _ [] = []
384 intersperse _ [x] = [x]
385 intersperse sep (x:xs) = x : sep : intersperse sep xs
387 -- | The 'transpose' function transposes the rows and columns of its argument.
390 -- > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]
392 transpose :: [[a]] -> [[a]]
394 transpose ([] : xss) = transpose xss
395 transpose ((x:xs) : xss) = (x : [h | (h:t) <- xss]) : transpose (xs : [ t | (h:t) <- xss])
398 -- | The 'partition' function takes a predicate a list and returns
399 -- the pair of lists of elements which do and do not satisfy the
400 -- predicate, respectively; i.e.,
402 -- > partition p xs == (filter p xs, filter (not . p) xs)
404 partition :: (a -> Bool) -> [a] -> ([a],[a])
405 {-# INLINE partition #-}
406 partition p xs = foldr (select p) ([],[]) xs
408 select p x ~(ts,fs) | p x = (x:ts,fs)
409 | otherwise = (ts, x:fs)
411 -- | The 'mapAccumL' function behaves like a combination of 'map' and
412 -- 'foldl'; it applies a function to each element of a list, passing
413 -- an accumulating parameter from left to right, and returning a final
414 -- value of this accumulator together with the new list.
415 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
416 -- and accumulator, returning new
417 -- accumulator and elt of result list
418 -> acc -- Initial accumulator
420 -> (acc, [y]) -- Final accumulator and result list
421 mapAccumL _ s [] = (s, [])
422 mapAccumL f s (x:xs) = (s'',y:ys)
423 where (s', y ) = f s x
424 (s'',ys) = mapAccumL f s' xs
426 -- | The 'mapAccumR' function behaves like a combination of 'map' and
427 -- 'foldr'; it applies a function to each element of a list, passing
428 -- an accumulating parameter from right to left, and returning a final
429 -- value of this accumulator together with the new list.
430 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
431 -- and accumulator, returning new
432 -- accumulator and elt of result list
433 -> acc -- Initial accumulator
435 -> (acc, [y]) -- Final accumulator and result list
436 mapAccumR _ s [] = (s, [])
437 mapAccumR f s (x:xs) = (s'', y:ys)
438 where (s'',y ) = f s' x
439 (s', ys) = mapAccumR f s xs
441 -- | The 'insert' function takes an element and a list and inserts the
442 -- element into the list at the last position where it is still less
443 -- than or equal to the next element. In particular, if the list
444 -- is sorted before the call, the result will also be sorted.
445 -- It is a special case of 'insertBy', which allows the programmer to
446 -- supply their own comparison function.
447 insert :: Ord a => a -> [a] -> [a]
448 insert e ls = insertBy (compare) e ls
450 -- | The non-overloaded version of 'insert'.
451 insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
452 insertBy _ x [] = [x]
453 insertBy cmp x ys@(y:ys')
455 GT -> y : insertBy cmp x ys'
458 -- | 'maximum' returns the maximum value from a list,
459 -- which must be non-empty, finite, and of an ordered type.
460 -- It is a special case of 'Data.List.maximumBy', which allows the
461 -- programmer to supply their own comparison function.
462 maximum :: (Ord a) => [a] -> a
463 maximum [] = errorEmptyList "maximum"
464 maximum xs = foldl1 max xs
467 "maximumInt" maximum = (strictMaximum :: [Int] -> Int);
468 "maximumInteger" maximum = (strictMaximum :: [Integer] -> Integer)
471 -- We can't make the overloaded version of maximum strict without
472 -- changing its semantics (max might not be strict), but we can for
473 -- the version specialised to 'Int'.
474 strictMaximum :: (Ord a) => [a] -> a
475 strictMaximum [] = errorEmptyList "maximum"
476 strictMaximum xs = foldl1' max xs
478 -- | 'minimum' returns the minimum value from a list,
479 -- which must be non-empty, finite, and of an ordered type.
480 -- It is a special case of 'Data.List.minimumBy', which allows the
481 -- programmer to supply their own comparison function.
482 minimum :: (Ord a) => [a] -> a
483 minimum [] = errorEmptyList "minimum"
484 minimum xs = foldl1 min xs
487 "minimumInt" minimum = (strictMinimum :: [Int] -> Int);
488 "minimumInteger" minimum = (strictMinimum :: [Integer] -> Integer)
491 strictMinimum :: (Ord a) => [a] -> a
492 strictMinimum [] = errorEmptyList "minimum"
493 strictMinimum xs = foldl1' min xs
495 -- | The 'maximumBy' function takes a comparison function and a list
496 -- and returns the greatest element of the list by the comparison function.
497 -- The list must be finite and non-empty.
498 maximumBy :: (a -> a -> Ordering) -> [a] -> a
499 maximumBy _ [] = error "List.maximumBy: empty list"
500 maximumBy cmp xs = foldl1 max xs
502 max x y = case cmp x y of
506 -- | The 'minimumBy' function takes a comparison function and a list
507 -- and returns the least element of the list by the comparison function.
508 -- The list must be finite and non-empty.
509 minimumBy :: (a -> a -> Ordering) -> [a] -> a
510 minimumBy _ [] = error "List.minimumBy: empty list"
511 minimumBy cmp xs = foldl1 min xs
513 min x y = case cmp x y of
517 -- | The 'genericLength' function is an overloaded version of 'length'. In
518 -- particular, instead of returning an 'Int', it returns any type which is
519 -- an instance of 'Num'. It is, however, less efficient than 'length'.
520 genericLength :: (Num i) => [b] -> i
522 genericLength (_:l) = 1 + genericLength l
524 -- | The 'genericTake' function is an overloaded version of 'take', which
525 -- accepts any 'Integral' value as the number of elements to take.
526 genericTake :: (Integral i) => i -> [a] -> [a]
528 genericTake _ [] = []
529 genericTake n (x:xs) | n > 0 = x : genericTake (n-1) xs
530 genericTake _ _ = error "List.genericTake: negative argument"
532 -- | The 'genericDrop' function is an overloaded version of 'drop', which
533 -- accepts any 'Integral' value as the number of elements to drop.
534 genericDrop :: (Integral i) => i -> [a] -> [a]
535 genericDrop 0 xs = xs
536 genericDrop _ [] = []
537 genericDrop n (_:xs) | n > 0 = genericDrop (n-1) xs
538 genericDrop _ _ = error "List.genericDrop: negative argument"
540 -- | The 'genericSplitAt' function is an overloaded version of 'splitAt', which
541 -- accepts any 'Integral' value as the position at which to split.
542 genericSplitAt :: (Integral i) => i -> [b] -> ([b],[b])
543 genericSplitAt 0 xs = ([],xs)
544 genericSplitAt _ [] = ([],[])
545 genericSplitAt n (x:xs) | n > 0 = (x:xs',xs'') where
546 (xs',xs'') = genericSplitAt (n-1) xs
547 genericSplitAt _ _ = error "List.genericSplitAt: negative argument"
549 -- | The 'genericIndex' function is an overloaded version of '!!', which
550 -- accepts any 'Integral' value as the index.
551 genericIndex :: (Integral a) => [b] -> a -> b
552 genericIndex (x:_) 0 = x
553 genericIndex (_:xs) n
554 | n > 0 = genericIndex xs (n-1)
555 | otherwise = error "List.genericIndex: negative argument."
556 genericIndex _ _ = error "List.genericIndex: index too large."
558 -- | The 'genericReplicate' function is an overloaded version of 'replicate',
559 -- which accepts any 'Integral' value as the number of repetitions to make.
560 genericReplicate :: (Integral i) => i -> a -> [a]
561 genericReplicate n x = genericTake n (repeat x)
563 -- | The 'zip4' function takes four lists and returns a list of
564 -- quadruples, analogous to 'zip'.
565 zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
566 zip4 = zipWith4 (,,,)
568 -- | The 'zip5' function takes five lists and returns a list of
569 -- five-tuples, analogous to 'zip'.
570 zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
571 zip5 = zipWith5 (,,,,)
573 -- | The 'zip6' function takes six lists and returns a list of six-tuples,
574 -- analogous to 'zip'.
575 zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
577 zip6 = zipWith6 (,,,,,)
579 -- | The 'zip7' function takes seven lists and returns a list of
580 -- seven-tuples, analogous to 'zip'.
581 zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
582 [g] -> [(a,b,c,d,e,f,g)]
583 zip7 = zipWith7 (,,,,,,)
585 -- | The 'zipWith4' function takes a function which combines four
586 -- elements, as well as four lists and returns a list of their point-wise
587 -- combination, analogous to 'zipWith'.
588 zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
589 zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
590 = z a b c d : zipWith4 z as bs cs ds
591 zipWith4 _ _ _ _ _ = []
593 -- | The 'zipWith5' function takes a function which combines five
594 -- elements, as well as five lists and returns a list of their point-wise
595 -- combination, analogous to 'zipWith'.
596 zipWith5 :: (a->b->c->d->e->f) ->
597 [a]->[b]->[c]->[d]->[e]->[f]
598 zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
599 = z a b c d e : zipWith5 z as bs cs ds es
600 zipWith5 _ _ _ _ _ _ = []
602 -- | The 'zipWith6' function takes a function which combines six
603 -- elements, as well as six lists and returns a list of their point-wise
604 -- combination, analogous to 'zipWith'.
605 zipWith6 :: (a->b->c->d->e->f->g) ->
606 [a]->[b]->[c]->[d]->[e]->[f]->[g]
607 zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
608 = z a b c d e f : zipWith6 z as bs cs ds es fs
609 zipWith6 _ _ _ _ _ _ _ = []
611 -- | The 'zipWith7' function takes a function which combines seven
612 -- elements, as well as seven lists and returns a list of their point-wise
613 -- combination, analogous to 'zipWith'.
614 zipWith7 :: (a->b->c->d->e->f->g->h) ->
615 [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
616 zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
617 = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
618 zipWith7 _ _ _ _ _ _ _ _ = []
620 -- | The 'unzip4' function takes a list of quadruples and returns four
621 -- lists, analogous to 'unzip'.
622 unzip4 :: [(a,b,c,d)] -> ([a],[b],[c],[d])
623 unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
624 (a:as,b:bs,c:cs,d:ds))
627 -- | The 'unzip5' function takes a list of five-tuples and returns five
628 -- lists, analogous to 'unzip'.
629 unzip5 :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
630 unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
631 (a:as,b:bs,c:cs,d:ds,e:es))
634 -- | The 'unzip6' function takes a list of six-tuples and returns six
635 -- lists, analogous to 'unzip'.
636 unzip6 :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
637 unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
638 (a:as,b:bs,c:cs,d:ds,e:es,f:fs))
641 -- | The 'unzip7' function takes a list of seven-tuples and returns
642 -- seven lists, analogous to 'unzip'.
643 unzip7 :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
644 unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
645 (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
646 ([],[],[],[],[],[],[])
649 -- | The 'deleteFirstsBy' function takes a predicate and two lists and
650 -- returns the first list with the first occurrence of each element of
651 -- the second list removed.
652 deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
653 deleteFirstsBy eq = foldl (flip (deleteBy eq))
655 -- | The 'group' function takes a list and returns a list of lists such
656 -- that the concatenation of the result is equal to the argument. Moreover,
657 -- each sublist in the result contains only equal elements. For example,
659 -- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
661 -- It is a special case of 'groupBy', which allows the programmer to supply
662 -- their own equality test.
663 group :: Eq a => [a] -> [[a]]
666 -- | The 'groupBy' function is the non-overloaded version of 'group'.
667 groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
669 groupBy eq (x:xs) = (x:ys) : groupBy eq zs
670 where (ys,zs) = span (eq x) xs
672 -- | The 'inits' function returns all initial segments of the argument,
673 -- shortest first. For example,
675 -- > inits "abc" == ["","a","ab","abc"]
677 inits :: [a] -> [[a]]
679 inits (x:xs) = [[]] ++ map (x:) (inits xs)
681 -- | The 'tails' function returns all final segments of the argument,
682 -- longest first. For example,
684 -- > tails "abc" == ["abc", "bc", "c",""]
686 tails :: [a] -> [[a]]
688 tails xxs@(_:xs) = xxs : tails xs
691 ------------------------------------------------------------------------------
692 -- Quick Sort algorithm taken from HBC's QSort library.
694 -- | The 'sort' function implements a stable sorting algorithm.
695 -- It is a special case of 'sortBy', which allows the programmer to supply
696 -- their own comparison function.
697 sort :: (Ord a) => [a] -> [a]
699 -- | The 'sortBy' function is the non-overloaded version of 'sort'.
700 sortBy :: (a -> a -> Ordering) -> [a] -> [a]
702 #ifdef USE_REPORT_PRELUDE
703 sort = sortBy compare
704 sortBy cmp = foldr (insertBy cmp) []
707 sortBy cmp l = mergesort cmp l
708 sort l = mergesort compare l
711 Quicksort replaced by mergesort, 14/5/2002.
713 From: Ian Lynagh <igloo@earth.li>
715 I am curious as to why the List.sort implementation in GHC is a
716 quicksort algorithm rather than an algorithm that guarantees n log n
717 time in the worst case? I have attached a mergesort implementation along
718 with a few scripts to time it's performance, the results of which are
719 shown below (* means it didn't finish successfully - in all cases this
720 was due to a stack overflow).
722 If I heap profile the random_list case with only 10000 then I see
723 random_list peaks at using about 2.5M of memory, whereas in the same
724 program using List.sort it uses only 100k.
726 Input style Input length Sort data Sort alg User time
727 stdin 10000 random_list sort 2.82
728 stdin 10000 random_list mergesort 2.96
729 stdin 10000 sorted sort 31.37
730 stdin 10000 sorted mergesort 1.90
731 stdin 10000 revsorted sort 31.21
732 stdin 10000 revsorted mergesort 1.88
733 stdin 100000 random_list sort *
734 stdin 100000 random_list mergesort *
735 stdin 100000 sorted sort *
736 stdin 100000 sorted mergesort *
737 stdin 100000 revsorted sort *
738 stdin 100000 revsorted mergesort *
739 func 10000 random_list sort 0.31
740 func 10000 random_list mergesort 0.91
741 func 10000 sorted sort 19.09
742 func 10000 sorted mergesort 0.15
743 func 10000 revsorted sort 19.17
744 func 10000 revsorted mergesort 0.16
745 func 100000 random_list sort 3.85
746 func 100000 random_list mergesort *
747 func 100000 sorted sort 5831.47
748 func 100000 sorted mergesort 2.23
749 func 100000 revsorted sort 5872.34
750 func 100000 revsorted mergesort 2.24
753 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
754 mergesort cmp = mergesort' cmp . map wrap
756 mergesort' :: (a -> a -> Ordering) -> [[a]] -> [a]
757 mergesort' cmp [] = []
758 mergesort' cmp [xs] = xs
759 mergesort' cmp xss = mergesort' cmp (merge_pairs cmp xss)
761 merge_pairs :: (a -> a -> Ordering) -> [[a]] -> [[a]]
762 merge_pairs cmp [] = []
763 merge_pairs cmp [xs] = [xs]
764 merge_pairs cmp (xs:ys:xss) = merge cmp xs ys : merge_pairs cmp xss
766 merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
769 merge cmp (x:xs) (y:ys)
771 GT -> y : merge cmp (x:xs) ys
772 _ -> x : merge cmp xs (y:ys)
780 -- qsort is stable and does not concatenate.
781 qsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
784 qsort cmp (x:xs) r = qpart cmp x xs [] [] r
786 -- qpart partitions and sorts the sublists
787 qpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]
788 qpart cmp x [] rlt rge r =
789 -- rlt and rge are in reverse order and must be sorted with an
790 -- anti-stable sorting
791 rqsort cmp rlt (x:rqsort cmp rge r)
792 qpart cmp x (y:ys) rlt rge r =
794 GT -> qpart cmp x ys (y:rlt) rge r
795 _ -> qpart cmp x ys rlt (y:rge) r
797 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
798 rqsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
801 rqsort cmp (x:xs) r = rqpart cmp x xs [] [] r
803 rqpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]
804 rqpart cmp x [] rle rgt r =
805 qsort cmp rle (x:qsort cmp rgt r)
806 rqpart cmp x (y:ys) rle rgt r =
808 GT -> rqpart cmp x ys rle (y:rgt) r
809 _ -> rqpart cmp x ys (y:rle) rgt r
812 #endif /* USE_REPORT_PRELUDE */
814 -- | The 'unfoldr' function is a \`dual\' to 'foldr': while 'foldr'
815 -- reduces a list to a summary value, 'unfoldr' builds a list from
816 -- a seed value. The function takes the element and returns 'Nothing'
817 -- if it is done producing the list or returns 'Just' @(a,b)@, in which
818 -- case, @a@ is a prepended to the list and @b@ is used as the next
819 -- element in a recursive call. For example,
821 -- > iterate f == unfoldr (\x -> Just (x, f x))
823 -- In some cases, 'unfoldr' can undo a 'foldr' operation:
825 -- > unfoldr f' (foldr f z xs) == xs
827 -- if the following holds:
829 -- > f' (f x y) = Just (x,y)
832 unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
835 Just (a,new_b) -> a : unfoldr f new_b
838 -- -----------------------------------------------------------------------------
840 -- | A strict version of 'foldl'.
841 foldl' :: (a -> b -> a) -> a -> [b] -> a
843 foldl' f a (x:xs) = let a' = f a x in a' `seq` foldl' f a' xs
845 -- | 'foldl1' is a variant of 'foldl' that has no starting value argument,
846 -- and thus must be applied to non-empty lists.
847 foldl1 :: (a -> a -> a) -> [a] -> a
848 foldl1 f (x:xs) = foldl f x xs
849 foldl1 _ [] = errorEmptyList "foldl1"
851 -- | A strict version of 'foldl1'
852 foldl1' :: (a -> a -> a) -> [a] -> a
853 foldl1' f (x:xs) = foldl' f x xs
854 foldl1' _ [] = errorEmptyList "foldl1'"
856 #ifdef __GLASGOW_HASKELL__
857 -- -----------------------------------------------------------------------------
858 -- List sum and product
860 {-# SPECIALISE sum :: [Int] -> Int #-}
861 {-# SPECIALISE sum :: [Integer] -> Integer #-}
862 {-# SPECIALISE product :: [Int] -> Int #-}
863 {-# SPECIALISE product :: [Integer] -> Integer #-}
864 -- | The 'sum' function computes the sum of a finite list of numbers.
865 sum :: (Num a) => [a] -> a
866 -- | The 'product' function computes the product of a finite list of numbers.
867 product :: (Num a) => [a] -> a
868 #ifdef USE_REPORT_PRELUDE
870 product = foldl (*) 1
875 sum' (x:xs) a = sum' xs (a+x)
879 prod (x:xs) a = prod xs (a*x)
882 -- -----------------------------------------------------------------------------
883 -- Functions on strings
885 -- | 'lines' breaks a string up into a list of strings at newline
886 -- characters. The resulting strings do not contain newlines.
887 lines :: String -> [String]
889 lines s = let (l, s') = break (== '\n') s
894 -- | 'unlines' is an inverse operation to 'lines'.
895 -- It joins lines, after appending a terminating newline to each.
896 unlines :: [String] -> String
897 #ifdef USE_REPORT_PRELUDE
898 unlines = concatMap (++ "\n")
900 -- HBC version (stolen)
901 -- here's a more efficient version
903 unlines (l:ls) = l ++ '\n' : unlines ls
906 -- | 'words' breaks a string up into a list of words, which were delimited
908 words :: String -> [String]
909 words s = case dropWhile {-partain:Char.-}isSpace s of
913 break {-partain:Char.-}isSpace s'
915 -- | 'unwords' is an inverse operation to 'words'.
916 -- It joins words with separating spaces.
917 unwords :: [String] -> String
918 #ifdef USE_REPORT_PRELUDE
920 unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
922 -- HBC version (stolen)
923 -- here's a more efficient version
926 unwords (w:ws) = w ++ ' ' : unwords ws
928 #endif /* __GLASGOW_HASKELL__ */