[project @ 2004-09-28 11:29:29 by simonmar]
[ghc-base.git] / Data / List.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Data.List
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  stable
10 -- Portability :  portable
11 --
12 -- Operations on lists.
13 --
14 -----------------------------------------------------------------------------
15
16 module Data.List
17    ( 
18 #ifdef __NHC__
19      [] (..)
20    ,
21 #endif
22
23    -- * Basic functions
24
25      (++)              -- :: [a] -> [a] -> [a]
26    , head              -- :: [a] -> a
27    , last              -- :: [a] -> a
28    , tail              -- :: [a] -> [a]
29    , init              -- :: [a] -> [a]
30    , null              -- :: [a] -> Bool
31    , length            -- :: [a] -> Int
32
33    -- * List transformations
34    , map               -- :: (a -> b) -> [a] -> [b]
35    , reverse           -- :: [a] -> [a]
36
37    , intersperse       -- :: a -> [a] -> [a]
38    , transpose         -- :: [[a]] -> [[a]]
39
40    -- * Reducing lists (folds)
41
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
48
49    -- ** Special folds
50
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
61
62    -- * Building lists
63
64    -- ** Scans
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]
69
70    -- ** Accumulating maps
71    , mapAccumL         -- :: (a -> b -> (a,c)) -> a -> [b] -> (a,[c])
72    , mapAccumR         -- :: (a -> b -> (a,c)) -> a -> [b] -> (a,[c])
73
74    -- ** Infinite lists
75    , iterate           -- :: (a -> a) -> a -> [a]
76    , repeat            -- :: a -> [a]
77    , replicate         -- :: Int -> a -> [a]
78    , cycle             -- :: [a] -> [a]
79
80    -- ** Unfolding
81    , unfoldr           -- :: (b -> Maybe (a, b)) -> b -> [a]
82
83    -- * Sublists
84
85    -- ** Extracting sublists
86    , take              -- :: Int -> [a] -> [a]
87    , drop              -- :: Int -> [a] -> [a]
88    , splitAt           -- :: Int -> [a] -> ([a], [a])
89
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])
94
95    , group             -- :: Eq a => [a] -> [[a]]
96
97    , inits             -- :: [a] -> [[a]]
98    , tails             -- :: [a] -> [[a]]
99
100    -- ** Predicates
101    , isPrefixOf        -- :: (Eq a) => [a] -> [a] -> Bool
102    , isSuffixOf        -- :: (Eq a) => [a] -> [a] -> Bool
103
104    -- * Searching lists
105
106    -- ** Searching by equality
107    , elem              -- :: a -> [a] -> Bool
108    , notElem           -- :: a -> [a] -> Bool
109    , lookup            -- :: (Eq a) => a -> [(a,b)] -> Maybe b
110
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])
115
116    -- * Indexing lists
117    -- | These functions treat a list @xs@ as a indexed collection,
118    -- with indices ranging from 0 to @'length' xs - 1@.
119
120    , (!!)              -- :: [a] -> Int -> a
121
122    , elemIndex         -- :: (Eq a) => a -> [a] -> Maybe Int
123    , elemIndices       -- :: (Eq a) => a -> [a] -> [Int]
124
125    , findIndex         -- :: (a -> Bool) -> [a] -> Maybe Int
126    , findIndices       -- :: (a -> Bool) -> [a] -> [Int]
127
128    -- * Zipping and unzipping lists
129
130    , zip               -- :: [a] -> [b] -> [(a,b)]
131    , zip3  
132    , zip4, zip5, zip6, zip7
133
134    , zipWith           -- :: (a -> b -> c) -> [a] -> [b] -> [c]
135    , zipWith3
136    , zipWith4, zipWith5, zipWith6, zipWith7
137
138    , unzip             -- :: [(a,b)] -> ([a],[b])
139    , unzip3
140    , unzip4, unzip5, unzip6, unzip7
141
142    -- * Special lists
143
144    -- ** Functions on strings
145    , lines             -- :: String   -> [String]
146    , words             -- :: String   -> [String]
147    , unlines           -- :: [String] -> String
148    , unwords           -- :: [String] -> String
149
150    -- ** \"Set\" operations
151    
152    , nub               -- :: (Eq a) => [a] -> [a]
153
154    , delete            -- :: (Eq a) => a -> [a] -> [a]
155    , (\\)              -- :: (Eq a) => [a] -> [a] -> [a]
156    
157    , union             -- :: (Eq a) => [a] -> [a] -> [a]
158    , intersect         -- :: (Eq a) => [a] -> [a] -> [a]
159
160    -- ** Ordered lists
161    , sort              -- :: (Ord a) => [a] -> [a]
162    , insert            -- :: (Ord a) => a -> [a] -> [a]
163
164    -- * Generalized functions
165
166    -- ** The \"@By@\" operations
167    -- | By convention, overloaded functions have a non-overloaded
168    -- counterpart whose name is suffixed with \`@By@\'.
169
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]]
178
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
185
186    -- ** The \"@generic@\" operations
187    -- | The prefix \`@generic@\' indicates an overloaded function that
188    -- is a generalized version of a "Prelude" function.
189
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]
196
197    ) where
198
199 #ifdef __NHC__
200 import Prelude hiding (Maybe(..))
201 #endif
202
203 import Data.Maybe
204 import Data.Char        ( isSpace )
205
206 #ifdef __GLASGOW_HASKELL__
207 import GHC.Num
208 import GHC.Real
209 import GHC.List
210 import GHC.Base
211 #endif
212
213 infix 5 \\ -- comment to fool cpp
214
215 -- -----------------------------------------------------------------------------
216 -- List functions
217
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==)
223
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==)
228
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
234
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
240
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]
244
245 #if defined(USE_REPORT_PRELUDE) || !defined(__GLASGOW_HASKELL__)
246 findIndices p xs = [ i | (x,i) <- zip xs [0..], p x]
247 #else
248 -- Efficient definition
249 findIndices p ls = loop 0# ls
250                  where
251                    loop _ [] = []
252                    loop n (x:xs) | p x       = I# n : loop (n +# 1#) xs
253                                  | otherwise = loop (n +# 1#) xs
254 #endif  /* USE_REPORT_PRELUDE */
255
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
262
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
268
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
276 nub                     =  nubBy (==)
277 #else
278 -- stolen from HBC
279 nub l                   = nub' l []             -- '
280   where
281     nub' [] _           = []                    -- '
282     nub' (x:xs) ls                              -- '
283         | x `elem` ls   = nub' xs ls            -- '
284         | otherwise     = x : nub' xs (x:ls)    -- '
285 #endif
286
287 -- | The 'nubBy' function behaves just like 'nub', except it uses a
288 -- user-supplied equality predicate instead of the overloaded '=='
289 -- function.
290 nubBy                   :: (a -> a -> Bool) -> [a] -> [a]
291 #ifdef USE_REPORT_PRELUDE
292 nubBy eq []             =  []
293 nubBy eq (x:xs)         =  x : nubBy eq (filter (\ y -> not (eq x y)) xs)
294 #else
295 nubBy eq l              = nubBy' l []
296   where
297     nubBy' [] _         = []
298     nubBy' (y:ys) xs
299        | elem_by eq y xs = nubBy' ys xs 
300        | otherwise       = y : nubBy' ys (y:xs)
301
302 -- Not exported:
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
310 #endif
311
312
313 -- | 'delete' @x@ removes the first occurrence of @x@ from its list argument.
314 -- For example,
315 --
316 -- > delete 'a' "banana" == "bnana"
317 --
318 -- It is a special case of 'deleteBy', which allows the programmer to
319 -- supply their own equality test.
320
321 delete                  :: (Eq a) => a -> [a] -> [a]
322 delete                  =  deleteBy (==)
323
324 -- | The 'deleteBy' function behaves like 'delete', but takes a
325 -- user-supplied equality predicate.
326 deleteBy                :: (a -> a -> Bool) -> a -> [a] -> [a]
327 deleteBy _  _ []        = []
328 deleteBy eq x (y:ys)    = if x `eq` y then ys else y : deleteBy eq x ys
329
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
333 --
334 -- > (xs ++ ys) \\ xs == ys.
335 --
336 -- It is a special case of 'deleteFirstsBy', which allows the programmer
337 -- to supply their own equality test.
338
339 (\\)                    :: (Eq a) => [a] -> [a] -> [a]
340 (\\)                    =  foldl (flip delete)
341
342 -- | The 'union' function returns the list union of the two lists.
343 -- For example,
344 --
345 -- > "dog" `union` "cow" == "dogcw"
346 --
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
349 -- the result.
350 -- It is a special case of 'unionBy', which allows the programmer to supply
351 -- their own equality test.
352
353 union                   :: (Eq a) => [a] -> [a] -> [a]
354 union                   = unionBy (==)
355
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
359
360 -- | The 'intersect' function takes the list intersection of two lists.
361 -- For example,
362 --
363 -- > [1,2,3,4] `intersect` [2,4,6,8] == [2,4]
364 --
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.
368
369 intersect               :: (Eq a) => [a] -> [a] -> [a]
370 intersect               =  intersectBy (==)
371
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]
375
376 -- | The 'intersperse' function takes an element and a list and
377 -- \`intersperses\' that element between the elements of the list.
378 -- For example,
379 --
380 -- > intersperse ',' "abcde" == "a,b,c,d,e"
381
382 intersperse             :: a -> [a] -> [a]
383 intersperse _   []      = []
384 intersperse _   [x]     = [x]
385 intersperse sep (x:xs)  = x : sep : intersperse sep xs
386
387 -- | The 'transpose' function transposes the rows and columns of its argument.
388 -- For example,
389 --
390 -- > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]
391
392 transpose               :: [[a]] -> [[a]]
393 transpose []             = []
394 transpose ([]   : xss)   = transpose xss
395 transpose ((x:xs) : xss) = (x : [h | (h:t) <- xss]) : transpose (xs : [ t | (h:t) <- xss])
396
397
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.,
401 --
402 -- > partition p xs == (filter p xs, filter (not . p) xs)
403
404 partition               :: (a -> Bool) -> [a] -> ([a],[a])
405 {-# INLINE partition #-}
406 partition p xs = foldr (select p) ([],[]) xs
407
408 select p x ~(ts,fs) | p x       = (x:ts,fs)
409                     | otherwise = (ts, x:fs)
410
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 
419           -> [x]            -- Input list
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
425
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
434             -> [x]              -- Input list
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
440
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
449
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')
454  = case cmp x y of
455      GT -> y : insertBy cmp x ys'
456      _  -> x : ys
457
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
465
466 {-# RULES 
467   "maximumInt"     maximum = (strictMaximum :: [Int]     -> Int);
468   "maximumInteger" maximum = (strictMaximum :: [Integer] -> Integer)
469  #-}
470
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
477
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
485
486 {-# RULES
487   "minimumInt"     minimum = (strictMinimum :: [Int]     -> Int);
488   "minimumInteger" minimum = (strictMinimum :: [Integer] -> Integer)
489  #-}
490
491 strictMinimum           :: (Ord a) => [a] -> a
492 strictMinimum []        =  errorEmptyList "minimum"
493 strictMinimum xs        =  foldl1' min xs
494
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
501                         where
502                            max x y = case cmp x y of
503                                         GT -> x
504                                         _  -> y
505
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
512                         where
513                            min x y = case cmp x y of
514                                         GT -> y
515                                         _  -> x
516
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
521 genericLength []        =  0
522 genericLength (_:l)     =  1 + genericLength l
523
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]
527 genericTake 0 _         =  []
528 genericTake _ []        =  []
529 genericTake n (x:xs) | n > 0  =  x : genericTake (n-1) xs
530 genericTake _  _        =  error "List.genericTake: negative argument"
531
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"
539
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"
548
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."
557
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)
562
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 (,,,)
567
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 (,,,,)
572
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] -> 
576                               [(a,b,c,d,e,f)]
577 zip6                    =  zipWith6 (,,,,,)
578
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 (,,,,,,)
584
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 _ _ _ _ _      =  []
592
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 _ _ _ _ _ _    = []
601
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 _ _ _ _ _ _ _  = []
610
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 _ _ _ _ _ _ _ _ = []
619
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))
625                                  ([],[],[],[])
626
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))
632                                  ([],[],[],[],[])
633
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))
639                                  ([],[],[],[],[],[])
640
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                          ([],[],[],[],[],[],[])
647
648
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))
654
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,
658 --
659 -- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
660 --
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]]
664 group                   =  groupBy (==)
665
666 -- | The 'groupBy' function is the non-overloaded version of 'group'.
667 groupBy                 :: (a -> a -> Bool) -> [a] -> [[a]]
668 groupBy _  []           =  []
669 groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs
670                            where (ys,zs) = span (eq x) xs
671
672 -- | The 'inits' function returns all initial segments of the argument,
673 -- shortest first.  For example,
674 --
675 -- > inits "abc" == ["","a","ab","abc"]
676 --
677 inits                   :: [a] -> [[a]]
678 inits []                =  [[]]
679 inits (x:xs)            =  [[]] ++ map (x:) (inits xs)
680
681 -- | The 'tails' function returns all final segments of the argument,
682 -- longest first.  For example,
683 --
684 -- > tails "abc" == ["abc", "bc", "c",""]
685 --
686 tails                   :: [a] -> [[a]]
687 tails []                =  [[]]
688 tails xxs@(_:xs)        =  xxs : tails xs
689
690
691 ------------------------------------------------------------------------------
692 -- Quick Sort algorithm taken from HBC's QSort library.
693
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]
698
699 -- | The 'sortBy' function is the non-overloaded version of 'sort'.
700 sortBy :: (a -> a -> Ordering) -> [a] -> [a]
701
702 #ifdef USE_REPORT_PRELUDE
703 sort = sortBy compare
704 sortBy cmp = foldr (insertBy cmp) []
705 #else
706
707 sortBy cmp l = mergesort cmp l
708 sort l = mergesort compare l
709
710 {-
711 Quicksort replaced by mergesort, 14/5/2002.
712
713 From: Ian Lynagh <igloo@earth.li>
714
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).
721
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.
725
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
751 -}
752
753 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
754 mergesort cmp = mergesort' cmp . map wrap
755
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)
760
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
765
766 merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
767 merge cmp xs [] = xs
768 merge cmp [] ys = ys
769 merge cmp (x:xs) (y:ys)
770  = case x `cmp` y of
771         GT -> y : merge cmp (x:xs)   ys
772         _  -> x : merge cmp    xs (y:ys)
773
774 wrap :: a -> [a]
775 wrap x = [x]
776
777 {-
778 OLD: qsort version
779
780 -- qsort is stable and does not concatenate.
781 qsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
782 qsort _   []     r = r
783 qsort _   [x]    r = x:r
784 qsort cmp (x:xs) r = qpart cmp x xs [] [] r
785
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 =
793     case cmp x y of
794         GT -> qpart cmp x ys (y:rlt) rge r
795         _  -> qpart cmp x ys rlt (y:rge) r
796
797 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
798 rqsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
799 rqsort _   []     r = r
800 rqsort _   [x]    r = x:r
801 rqsort cmp (x:xs) r = rqpart cmp x xs [] [] r
802
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 =
807     case cmp y x of
808         GT -> rqpart cmp x ys rle (y:rgt) r
809         _  -> rqpart cmp x ys (y:rle) rgt r
810 -}
811
812 #endif /* USE_REPORT_PRELUDE */
813
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,
820 --
821 -- > iterate f == unfoldr (\x -> Just (x, f x))
822 --
823 -- In some cases, 'unfoldr' can undo a 'foldr' operation:
824 --
825 -- > unfoldr f' (foldr f z xs) == xs
826 --
827 -- if the following holds:
828 --
829 -- > f' (f x y) = Just (x,y)
830 -- > f' z       = Nothing
831
832 unfoldr      :: (b -> Maybe (a, b)) -> b -> [a]
833 unfoldr f b  =
834   case f b of
835    Just (a,new_b) -> a : unfoldr f new_b
836    Nothing        -> []
837
838 -- -----------------------------------------------------------------------------
839
840 -- | A strict version of 'foldl'.
841 foldl'           :: (a -> b -> a) -> a -> [b] -> a
842 foldl' f a []     = a
843 foldl' f a (x:xs) = let a' = f a x in a' `seq` foldl' f a' xs
844
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"
850
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'"
855
856 #ifdef __GLASGOW_HASKELL__
857 -- -----------------------------------------------------------------------------
858 -- List sum and product
859
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
869 sum                     =  foldl (+) 0  
870 product                 =  foldl (*) 1
871 #else
872 sum     l       = sum' l 0
873   where
874     sum' []     a = a
875     sum' (x:xs) a = sum' xs (a+x)
876 product l       = prod l 1
877   where
878     prod []     a = a
879     prod (x:xs) a = prod xs (a*x)
880 #endif
881
882 -- -----------------------------------------------------------------------------
883 -- Functions on strings
884
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]
888 lines ""                =  []
889 lines s                 =  let (l, s') = break (== '\n') s
890                            in  l : case s' of
891                                         []      -> []
892                                         (_:s'') -> lines s''
893
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")
899 #else
900 -- HBC version (stolen)
901 -- here's a more efficient version
902 unlines [] = []
903 unlines (l:ls) = l ++ '\n' : unlines ls
904 #endif
905
906 -- | 'words' breaks a string up into a list of words, which were delimited
907 -- by white space.
908 words                   :: String -> [String]
909 words s                 =  case dropWhile {-partain:Char.-}isSpace s of
910                                 "" -> []
911                                 s' -> w : words s''
912                                       where (w, s'') = 
913                                              break {-partain:Char.-}isSpace s'
914
915 -- | 'unwords' is an inverse operation to 'words'.
916 -- It joins words with separating spaces.
917 unwords                 :: [String] -> String
918 #ifdef USE_REPORT_PRELUDE
919 unwords []              =  ""
920 unwords ws              =  foldr1 (\w s -> w ++ ' ':s) ws
921 #else
922 -- HBC version (stolen)
923 -- here's a more efficient version
924 unwords []              =  ""
925 unwords [w]             = w
926 unwords (w:ws)          = w ++ ' ' : unwords ws
927 #endif
928 #endif  /* __GLASGOW_HASKELL__ */