137ce42150201b1fe57453019a8183dc8ce7fd10
[ghc.git] / libraries / base / Data / OldList.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Data.List
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : stable
12 -- Portability : portable
13 --
14 -- Operations on lists.
15 --
16 -----------------------------------------------------------------------------
17
18 module Data.OldList
19 (
20 -- * Basic functions
21
22 (++)
23 , head
24 , last
25 , tail
26 , init
27 , uncons
28 , null
29 , length
30
31 -- * List transformations
32 , map
33 , reverse
34
35 , intersperse
36 , intercalate
37 , transpose
38
39 , subsequences
40 , permutations
41
42 -- * Reducing lists (folds)
43
44 , foldl
45 , foldl'
46 , foldl1
47 , foldl1'
48 , foldr
49 , foldr1
50
51 -- ** Special folds
52
53 , concat
54 , concatMap
55 , and
56 , or
57 , any
58 , all
59 , sum
60 , product
61 , maximum
62 , minimum
63
64 -- * Building lists
65
66 -- ** Scans
67 , scanl
68 , scanl'
69 , scanl1
70 , scanr
71 , scanr1
72
73 -- ** Accumulating maps
74 , mapAccumL
75 , mapAccumR
76
77 -- ** Infinite lists
78 , iterate
79 , repeat
80 , replicate
81 , cycle
82
83 -- ** Unfolding
84 , unfoldr
85
86 -- * Sublists
87
88 -- ** Extracting sublists
89 , take
90 , drop
91 , splitAt
92
93 , takeWhile
94 , dropWhile
95 , dropWhileEnd
96 , span
97 , break
98
99 , stripPrefix
100
101 , group
102
103 , inits
104 , tails
105
106 -- ** Predicates
107 , isPrefixOf
108 , isSuffixOf
109 , isInfixOf
110
111 -- * Searching lists
112
113 -- ** Searching by equality
114 , elem
115 , notElem
116 , lookup
117
118 -- ** Searching with a predicate
119 , find
120 , filter
121 , partition
122
123 -- * Indexing lists
124 -- | These functions treat a list @xs@ as a indexed collection,
125 -- with indices ranging from 0 to @'length' xs - 1@.
126
127 , (!!)
128
129 , elemIndex
130 , elemIndices
131
132 , findIndex
133 , findIndices
134
135 -- * Zipping and unzipping lists
136
137 , zip
138 , zip3
139 , zip4, zip5, zip6, zip7
140
141 , zipWith
142 , zipWith3
143 , zipWith4, zipWith5, zipWith6, zipWith7
144
145 , unzip
146 , unzip3
147 , unzip4, unzip5, unzip6, unzip7
148
149 -- * Special lists
150
151 -- ** Functions on strings
152 , lines
153 , words
154 , unlines
155 , unwords
156
157 -- ** \"Set\" operations
158
159 , nub
160
161 , delete
162 , (\\)
163
164 , union
165 , intersect
166
167 -- ** Ordered lists
168 , sort
169 , sortOn
170 , insert
171
172 -- * Generalized functions
173
174 -- ** The \"@By@\" operations
175 -- | By convention, overloaded functions have a non-overloaded
176 -- counterpart whose name is suffixed with \`@By@\'.
177 --
178 -- It is often convenient to use these functions together with
179 -- 'Data.Function.on', for instance @'sortBy' ('compare'
180 -- \`on\` 'fst')@.
181
182 -- *** User-supplied equality (replacing an @Eq@ context)
183 -- | The predicate is assumed to define an equivalence.
184 , nubBy
185 , deleteBy
186 , deleteFirstsBy
187 , unionBy
188 , intersectBy
189 , groupBy
190
191 -- *** User-supplied comparison (replacing an @Ord@ context)
192 -- | The function is assumed to define a total ordering.
193 , sortBy
194 , insertBy
195 , maximumBy
196 , minimumBy
197
198 -- ** The \"@generic@\" operations
199 -- | The prefix \`@generic@\' indicates an overloaded function that
200 -- is a generalized version of a "Prelude" function.
201
202 , genericLength
203 , genericTake
204 , genericDrop
205 , genericSplitAt
206 , genericIndex
207 , genericReplicate
208
209 ) where
210
211 import Data.Maybe
212 import Data.Bits ( (.&.) )
213 import Data.Char ( isSpace )
214 import Data.Ord ( comparing )
215 import Data.Tuple ( fst, snd )
216
217 import GHC.Num
218 import GHC.Real
219 import GHC.List
220 import GHC.Base
221
222 infix 5 \\ -- comment to fool cpp: https://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#cpp-string-gaps
223
224 -- -----------------------------------------------------------------------------
225 -- List functions
226
227 -- | The 'dropWhileEnd' function drops the largest suffix of a list
228 -- in which the given predicate holds for all elements. For example:
229 --
230 -- > dropWhileEnd isSpace "foo\n" == "foo"
231 -- > dropWhileEnd isSpace "foo bar" == "foo bar"
232 -- > dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
233 --
234 -- @since 4.5.0.0
235 dropWhileEnd :: (a -> Bool) -> [a] -> [a]
236 dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) []
237
238 -- | The 'stripPrefix' function drops the given prefix from a list.
239 -- It returns 'Nothing' if the list did not start with the prefix
240 -- given, or 'Just' the list after the prefix, if it does.
241 --
242 -- > stripPrefix "foo" "foobar" == Just "bar"
243 -- > stripPrefix "foo" "foo" == Just ""
244 -- > stripPrefix "foo" "barfoo" == Nothing
245 -- > stripPrefix "foo" "barfoobaz" == Nothing
246 stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
247 stripPrefix [] ys = Just ys
248 stripPrefix (x:xs) (y:ys)
249 | x == y = stripPrefix xs ys
250 stripPrefix _ _ = Nothing
251
252 -- | The 'elemIndex' function returns the index of the first element
253 -- in the given list which is equal (by '==') to the query element,
254 -- or 'Nothing' if there is no such element.
255 elemIndex :: Eq a => a -> [a] -> Maybe Int
256 elemIndex x = findIndex (x==)
257
258 -- | The 'elemIndices' function extends 'elemIndex', by returning the
259 -- indices of all elements equal to the query element, in ascending order.
260 elemIndices :: Eq a => a -> [a] -> [Int]
261 elemIndices x = findIndices (x==)
262
263 -- | The 'find' function takes a predicate and a list and returns the
264 -- first element in the list matching the predicate, or 'Nothing' if
265 -- there is no such element.
266 find :: (a -> Bool) -> [a] -> Maybe a
267 find p = listToMaybe . filter p
268
269 -- | The 'findIndex' function takes a predicate and a list and returns
270 -- the index of the first element in the list satisfying the predicate,
271 -- or 'Nothing' if there is no such element.
272 findIndex :: (a -> Bool) -> [a] -> Maybe Int
273 findIndex p = listToMaybe . findIndices p
274
275 -- | The 'findIndices' function extends 'findIndex', by returning the
276 -- indices of all elements satisfying the predicate, in ascending order.
277 findIndices :: (a -> Bool) -> [a] -> [Int]
278 #ifdef USE_REPORT_PRELUDE
279 findIndices p xs = [ i | (x,i) <- zip xs [0..], p x]
280 #else
281 -- Efficient definition, adapted from Data.Sequence
282 {-# INLINE findIndices #-}
283 findIndices p ls = build $ \c n ->
284 let go x r k | p x = I# k `c` r (k +# 1#)
285 | otherwise = r (k +# 1#)
286 in foldr go (\_ -> n) ls 0#
287 #endif /* USE_REPORT_PRELUDE */
288
289 -- | The 'isPrefixOf' function takes two lists and returns 'True'
290 -- iff the first list is a prefix of the second.
291 isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
292 isPrefixOf [] _ = True
293 isPrefixOf _ [] = False
294 isPrefixOf (x:xs) (y:ys)= x == y && isPrefixOf xs ys
295
296 -- | The 'isSuffixOf' function takes two lists and returns 'True' iff
297 -- the first list is a suffix of the second. The second list must be
298 -- finite.
299 isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
300 ns `isSuffixOf` hs = maybe False id $ do
301 delta <- dropLengthMaybe ns hs
302 return $ ns == dropLength delta hs
303 -- Since dropLengthMaybe ns hs succeeded, we know that (if hs is finite)
304 -- length ns + length delta = length hs
305 -- so dropping the length of delta from hs will yield a suffix exactly
306 -- the length of ns.
307
308 -- A version of drop that drops the length of the first argument from the
309 -- second argument. If xs is longer than ys, xs will not be traversed in its
310 -- entirety. dropLength is also generally faster than (drop . length)
311 -- Both this and dropLengthMaybe could be written as folds over their first
312 -- arguments, but this reduces clarity with no benefit to isSuffixOf.
313 dropLength :: [a] -> [b] -> [b]
314 dropLength [] y = y
315 dropLength _ [] = []
316 dropLength (_:x') (_:y') = dropLength x' y'
317
318 -- A version of dropLength that returns Nothing if the second list runs out of
319 -- elements before the first.
320 dropLengthMaybe :: [a] -> [b] -> Maybe [b]
321 dropLengthMaybe [] y = Just y
322 dropLengthMaybe _ [] = Nothing
323 dropLengthMaybe (_:x') (_:y') = dropLengthMaybe x' y'
324
325 -- | The 'isInfixOf' function takes two lists and returns 'True'
326 -- iff the first list is contained, wholly and intact,
327 -- anywhere within the second.
328 --
329 -- Example:
330 --
331 -- >isInfixOf "Haskell" "I really like Haskell." == True
332 -- >isInfixOf "Ial" "I really like Haskell." == False
333 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
334 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
335
336 -- | /O(n^2)/. The 'nub' function removes duplicate elements from a list.
337 -- In particular, it keeps only the first occurrence of each element.
338 -- (The name 'nub' means \`essence\'.)
339 -- It is a special case of 'nubBy', which allows the programmer to supply
340 -- their own equality test.
341 nub :: (Eq a) => [a] -> [a]
342 nub = nubBy (==)
343
344 -- | The 'nubBy' function behaves just like 'nub', except it uses a
345 -- user-supplied equality predicate instead of the overloaded '=='
346 -- function.
347 nubBy :: (a -> a -> Bool) -> [a] -> [a]
348 #ifdef USE_REPORT_PRELUDE
349 nubBy eq [] = []
350 nubBy eq (x:xs) = x : nubBy eq (filter (\ y -> not (eq x y)) xs)
351 #else
352 -- stolen from HBC
353 nubBy eq l = nubBy' l []
354 where
355 nubBy' [] _ = []
356 nubBy' (y:ys) xs
357 | elem_by eq y xs = nubBy' ys xs
358 | otherwise = y : nubBy' ys (y:xs)
359
360 -- Not exported:
361 -- Note that we keep the call to `eq` with arguments in the
362 -- same order as in the reference (prelude) implementation,
363 -- and that this order is different from how `elem` calls (==).
364 -- See #2528, #3280 and #7913.
365 -- 'xs' is the list of things we've seen so far,
366 -- 'y' is the potential new element
367 elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool
368 elem_by _ _ [] = False
369 elem_by eq y (x:xs) = x `eq` y || elem_by eq y xs
370 #endif
371
372
373 -- | 'delete' @x@ removes the first occurrence of @x@ from its list argument.
374 -- For example,
375 --
376 -- > delete 'a' "banana" == "bnana"
377 --
378 -- It is a special case of 'deleteBy', which allows the programmer to
379 -- supply their own equality test.
380
381 delete :: (Eq a) => a -> [a] -> [a]
382 delete = deleteBy (==)
383
384 -- | The 'deleteBy' function behaves like 'delete', but takes a
385 -- user-supplied equality predicate.
386 deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
387 deleteBy _ _ [] = []
388 deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
389
390 -- | The '\\' function is list difference (non-associative).
391 -- In the result of @xs@ '\\' @ys@, the first occurrence of each element of
392 -- @ys@ in turn (if any) has been removed from @xs@. Thus
393 --
394 -- > (xs ++ ys) \\ xs == ys.
395 --
396 -- It is a special case of 'deleteFirstsBy', which allows the programmer
397 -- to supply their own equality test.
398
399 (\\) :: (Eq a) => [a] -> [a] -> [a]
400 (\\) = foldl (flip delete)
401
402 -- | The 'union' function returns the list union of the two lists.
403 -- For example,
404 --
405 -- > "dog" `union` "cow" == "dogcw"
406 --
407 -- Duplicates, and elements of the first list, are removed from the
408 -- the second list, but if the first list contains duplicates, so will
409 -- the result.
410 -- It is a special case of 'unionBy', which allows the programmer to supply
411 -- their own equality test.
412
413 union :: (Eq a) => [a] -> [a] -> [a]
414 union = unionBy (==)
415
416 -- | The 'unionBy' function is the non-overloaded version of 'union'.
417 unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
418 unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs
419
420 -- | The 'intersect' function takes the list intersection of two lists.
421 -- For example,
422 --
423 -- > [1,2,3,4] `intersect` [2,4,6,8] == [2,4]
424 --
425 -- If the first list contains duplicates, so will the result.
426 --
427 -- > [1,2,2,3,4] `intersect` [6,4,4,2] == [2,2,4]
428 --
429 -- It is a special case of 'intersectBy', which allows the programmer to
430 -- supply their own equality test. If the element is found in both the first
431 -- and the second list, the element from the first list will be used.
432
433 intersect :: (Eq a) => [a] -> [a] -> [a]
434 intersect = intersectBy (==)
435
436 -- | The 'intersectBy' function is the non-overloaded version of 'intersect'.
437 intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
438 intersectBy _ [] _ = []
439 intersectBy _ _ [] = []
440 intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
441
442 -- | The 'intersperse' function takes an element and a list and
443 -- \`intersperses\' that element between the elements of the list.
444 -- For example,
445 --
446 -- > intersperse ',' "abcde" == "a,b,c,d,e"
447
448 intersperse :: a -> [a] -> [a]
449 intersperse _ [] = []
450 intersperse sep (x:xs) = x : prependToAll sep xs
451
452
453 -- Not exported:
454 -- We want to make every element in the 'intersperse'd list available
455 -- as soon as possible to avoid space leaks. Experiments suggested that
456 -- a separate top-level helper is more efficient than a local worker.
457 prependToAll :: a -> [a] -> [a]
458 prependToAll _ [] = []
459 prependToAll sep (x:xs) = sep : x : prependToAll sep xs
460
461 -- | 'intercalate' @xs xss@ is equivalent to @('concat' ('intersperse' xs xss))@.
462 -- It inserts the list @xs@ in between the lists in @xss@ and concatenates the
463 -- result.
464 intercalate :: [a] -> [[a]] -> [a]
465 intercalate xs xss = concat (intersperse xs xss)
466
467 -- | The 'transpose' function transposes the rows and columns of its argument.
468 -- For example,
469 --
470 -- > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]
471
472 transpose :: [[a]] -> [[a]]
473 transpose [] = []
474 transpose ([] : xss) = transpose xss
475 transpose ((x:xs) : xss) = (x : [h | (h:_) <- xss]) : transpose (xs : [ t | (_:t) <- xss])
476
477
478 -- | The 'partition' function takes a predicate a list and returns
479 -- the pair of lists of elements which do and do not satisfy the
480 -- predicate, respectively; i.e.,
481 --
482 -- > partition p xs == (filter p xs, filter (not . p) xs)
483
484 partition :: (a -> Bool) -> [a] -> ([a],[a])
485 {-# INLINE partition #-}
486 partition p xs = foldr (select p) ([],[]) xs
487
488 select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a])
489 select p x ~(ts,fs) | p x = (x:ts,fs)
490 | otherwise = (ts, x:fs)
491
492 -- | The 'mapAccumL' function behaves like a combination of 'map' and
493 -- 'foldl'; it applies a function to each element of a list, passing
494 -- an accumulating parameter from left to right, and returning a final
495 -- value of this accumulator together with the new list.
496 mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list
497 -- and accumulator, returning new
498 -- accumulator and elt of result list
499 -> acc -- Initial accumulator
500 -> [x] -- Input list
501 -> (acc, [y]) -- Final accumulator and result list
502 {-# NOINLINE [1] mapAccumL #-}
503 mapAccumL _ s [] = (s, [])
504 mapAccumL f s (x:xs) = (s'',y:ys)
505 where (s', y ) = f s x
506 (s'',ys) = mapAccumL f s' xs
507
508 {-# RULES
509 "mapAccumL" [~1] forall f s xs . mapAccumL f s xs = foldr (mapAccumLF f) pairWithNil xs s
510 "mapAccumLList" [1] forall f s xs . foldr (mapAccumLF f) pairWithNil xs s = mapAccumL f s xs
511 #-}
512
513 pairWithNil :: acc -> (acc, [y])
514 {-# INLINE [0] pairWithNil #-}
515 pairWithNil x = (x, [])
516
517 mapAccumLF :: (acc -> x -> (acc, y)) -> x -> (acc -> (acc, [y])) -> acc -> (acc, [y])
518 {-# INLINE [0] mapAccumLF #-}
519 mapAccumLF f = \x r -> oneShot (\s ->
520 let (s', y) = f s x
521 (s'', ys) = r s'
522 in (s'', y:ys))
523 -- See Note [Left folds via right fold]
524
525
526 -- | The 'mapAccumR' function behaves like a combination of 'map' and
527 -- 'foldr'; it applies a function to each element of a list, passing
528 -- an accumulating parameter from right to left, and returning a final
529 -- value of this accumulator together with the new list.
530 mapAccumR :: (acc -> x -> (acc, y)) -- Function of elt of input list
531 -- and accumulator, returning new
532 -- accumulator and elt of result list
533 -> acc -- Initial accumulator
534 -> [x] -- Input list
535 -> (acc, [y]) -- Final accumulator and result list
536 mapAccumR _ s [] = (s, [])
537 mapAccumR f s (x:xs) = (s'', y:ys)
538 where (s'',y ) = f s' x
539 (s', ys) = mapAccumR f s xs
540
541 -- | The 'insert' function takes an element and a list and inserts the
542 -- element into the list at the first position where it is less
543 -- than or equal to the next element. In particular, if the list
544 -- is sorted before the call, the result will also be sorted.
545 -- It is a special case of 'insertBy', which allows the programmer to
546 -- supply their own comparison function.
547 insert :: Ord a => a -> [a] -> [a]
548 insert e ls = insertBy (compare) e ls
549
550 -- | The non-overloaded version of 'insert'.
551 insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
552 insertBy _ x [] = [x]
553 insertBy cmp x ys@(y:ys')
554 = case cmp x y of
555 GT -> y : insertBy cmp x ys'
556 _ -> x : ys
557
558 -- | The 'maximumBy' function takes a comparison function and a list
559 -- and returns the greatest element of the list by the comparison function.
560 -- The list must be finite and non-empty.
561 maximumBy :: (a -> a -> Ordering) -> [a] -> a
562 maximumBy _ [] = error "List.maximumBy: empty list"
563 maximumBy cmp xs = foldl1 maxBy xs
564 where
565 maxBy x y = case cmp x y of
566 GT -> x
567 _ -> y
568
569 -- | The 'minimumBy' function takes a comparison function and a list
570 -- and returns the least element of the list by the comparison function.
571 -- The list must be finite and non-empty.
572 minimumBy :: (a -> a -> Ordering) -> [a] -> a
573 minimumBy _ [] = error "List.minimumBy: empty list"
574 minimumBy cmp xs = foldl1 minBy xs
575 where
576 minBy x y = case cmp x y of
577 GT -> y
578 _ -> x
579
580 -- | The 'genericLength' function is an overloaded version of 'length'. In
581 -- particular, instead of returning an 'Int', it returns any type which is
582 -- an instance of 'Num'. It is, however, less efficient than 'length'.
583 genericLength :: (Num i) => [a] -> i
584 {-# NOINLINE [1] genericLength #-}
585 genericLength [] = 0
586 genericLength (_:l) = 1 + genericLength l
587
588 {-# RULES
589 "genericLengthInt" genericLength = (strictGenericLength :: [a] -> Int);
590 "genericLengthInteger" genericLength = (strictGenericLength :: [a] -> Integer);
591 #-}
592
593 strictGenericLength :: (Num i) => [b] -> i
594 strictGenericLength l = gl l 0
595 where
596 gl [] a = a
597 gl (_:xs) a = let a' = a + 1 in a' `seq` gl xs a'
598
599 -- | The 'genericTake' function is an overloaded version of 'take', which
600 -- accepts any 'Integral' value as the number of elements to take.
601 genericTake :: (Integral i) => i -> [a] -> [a]
602 genericTake n _ | n <= 0 = []
603 genericTake _ [] = []
604 genericTake n (x:xs) = x : genericTake (n-1) xs
605
606 -- | The 'genericDrop' function is an overloaded version of 'drop', which
607 -- accepts any 'Integral' value as the number of elements to drop.
608 genericDrop :: (Integral i) => i -> [a] -> [a]
609 genericDrop n xs | n <= 0 = xs
610 genericDrop _ [] = []
611 genericDrop n (_:xs) = genericDrop (n-1) xs
612
613
614 -- | The 'genericSplitAt' function is an overloaded version of 'splitAt', which
615 -- accepts any 'Integral' value as the position at which to split.
616 genericSplitAt :: (Integral i) => i -> [a] -> ([a], [a])
617 genericSplitAt n xs | n <= 0 = ([],xs)
618 genericSplitAt _ [] = ([],[])
619 genericSplitAt n (x:xs) = (x:xs',xs'') where
620 (xs',xs'') = genericSplitAt (n-1) xs
621
622 -- | The 'genericIndex' function is an overloaded version of '!!', which
623 -- accepts any 'Integral' value as the index.
624 genericIndex :: (Integral i) => [a] -> i -> a
625 genericIndex (x:_) 0 = x
626 genericIndex (_:xs) n
627 | n > 0 = genericIndex xs (n-1)
628 | otherwise = error "List.genericIndex: negative argument."
629 genericIndex _ _ = error "List.genericIndex: index too large."
630
631 -- | The 'genericReplicate' function is an overloaded version of 'replicate',
632 -- which accepts any 'Integral' value as the number of repetitions to make.
633 genericReplicate :: (Integral i) => i -> a -> [a]
634 genericReplicate n x = genericTake n (repeat x)
635
636 -- | The 'zip4' function takes four lists and returns a list of
637 -- quadruples, analogous to 'zip'.
638 zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
639 zip4 = zipWith4 (,,,)
640
641 -- | The 'zip5' function takes five lists and returns a list of
642 -- five-tuples, analogous to 'zip'.
643 zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
644 zip5 = zipWith5 (,,,,)
645
646 -- | The 'zip6' function takes six lists and returns a list of six-tuples,
647 -- analogous to 'zip'.
648 zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
649 [(a,b,c,d,e,f)]
650 zip6 = zipWith6 (,,,,,)
651
652 -- | The 'zip7' function takes seven lists and returns a list of
653 -- seven-tuples, analogous to 'zip'.
654 zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
655 [g] -> [(a,b,c,d,e,f,g)]
656 zip7 = zipWith7 (,,,,,,)
657
658 -- | The 'zipWith4' function takes a function which combines four
659 -- elements, as well as four lists and returns a list of their point-wise
660 -- combination, analogous to 'zipWith'.
661 zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
662 zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
663 = z a b c d : zipWith4 z as bs cs ds
664 zipWith4 _ _ _ _ _ = []
665
666 -- | The 'zipWith5' function takes a function which combines five
667 -- elements, as well as five lists and returns a list of their point-wise
668 -- combination, analogous to 'zipWith'.
669 zipWith5 :: (a->b->c->d->e->f) ->
670 [a]->[b]->[c]->[d]->[e]->[f]
671 zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
672 = z a b c d e : zipWith5 z as bs cs ds es
673 zipWith5 _ _ _ _ _ _ = []
674
675 -- | The 'zipWith6' function takes a function which combines six
676 -- elements, as well as six lists and returns a list of their point-wise
677 -- combination, analogous to 'zipWith'.
678 zipWith6 :: (a->b->c->d->e->f->g) ->
679 [a]->[b]->[c]->[d]->[e]->[f]->[g]
680 zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
681 = z a b c d e f : zipWith6 z as bs cs ds es fs
682 zipWith6 _ _ _ _ _ _ _ = []
683
684 -- | The 'zipWith7' function takes a function which combines seven
685 -- elements, as well as seven lists and returns a list of their point-wise
686 -- combination, analogous to 'zipWith'.
687 zipWith7 :: (a->b->c->d->e->f->g->h) ->
688 [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
689 zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
690 = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
691 zipWith7 _ _ _ _ _ _ _ _ = []
692
693 -- | The 'unzip4' function takes a list of quadruples and returns four
694 -- lists, analogous to 'unzip'.
695 unzip4 :: [(a,b,c,d)] -> ([a],[b],[c],[d])
696 unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
697 (a:as,b:bs,c:cs,d:ds))
698 ([],[],[],[])
699
700 -- | The 'unzip5' function takes a list of five-tuples and returns five
701 -- lists, analogous to 'unzip'.
702 unzip5 :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
703 unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
704 (a:as,b:bs,c:cs,d:ds,e:es))
705 ([],[],[],[],[])
706
707 -- | The 'unzip6' function takes a list of six-tuples and returns six
708 -- lists, analogous to 'unzip'.
709 unzip6 :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
710 unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
711 (a:as,b:bs,c:cs,d:ds,e:es,f:fs))
712 ([],[],[],[],[],[])
713
714 -- | The 'unzip7' function takes a list of seven-tuples and returns
715 -- seven lists, analogous to 'unzip'.
716 unzip7 :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
717 unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
718 (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
719 ([],[],[],[],[],[],[])
720
721
722 -- | The 'deleteFirstsBy' function takes a predicate and two lists and
723 -- returns the first list with the first occurrence of each element of
724 -- the second list removed.
725 deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
726 deleteFirstsBy eq = foldl (flip (deleteBy eq))
727
728 -- | The 'group' function takes a list and returns a list of lists such
729 -- that the concatenation of the result is equal to the argument. Moreover,
730 -- each sublist in the result contains only equal elements. For example,
731 --
732 -- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
733 --
734 -- It is a special case of 'groupBy', which allows the programmer to supply
735 -- their own equality test.
736 group :: Eq a => [a] -> [[a]]
737 group = groupBy (==)
738
739 -- | The 'groupBy' function is the non-overloaded version of 'group'.
740 groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
741 groupBy _ [] = []
742 groupBy eq (x:xs) = (x:ys) : groupBy eq zs
743 where (ys,zs) = span (eq x) xs
744
745 -- | The 'inits' function returns all initial segments of the argument,
746 -- shortest first. For example,
747 --
748 -- > inits "abc" == ["","a","ab","abc"]
749 --
750 -- Note that 'inits' has the following strictness property:
751 -- @inits (xs ++ _|_) = inits xs ++ _|_@
752 --
753 -- In particular,
754 -- @inits _|_ = [] : _|_@
755 inits :: [a] -> [[a]]
756 inits = map toListSB . scanl' snocSB emptySB
757 {-# NOINLINE inits #-}
758
759 -- We do not allow inits to inline, because it plays havoc with Call Arity
760 -- if it fuses with a consumer, and it would generally lead to serious
761 -- loss of sharing if allowed to fuse with a producer.
762
763 -- | The 'tails' function returns all final segments of the argument,
764 -- longest first. For example,
765 --
766 -- > tails "abc" == ["abc", "bc", "c",""]
767 --
768 -- Note that 'tails' has the following strictness property:
769 -- @tails _|_ = _|_ : _|_@
770 tails :: [a] -> [[a]]
771 {-# INLINABLE tails #-}
772 tails lst = build (\c n ->
773 let tailsGo xs = xs `c` case xs of
774 [] -> n
775 _ : xs' -> tailsGo xs'
776 in tailsGo lst)
777
778 -- | The 'subsequences' function returns the list of all subsequences of the argument.
779 --
780 -- > subsequences "abc" == ["","a","b","ab","c","ac","bc","abc"]
781 subsequences :: [a] -> [[a]]
782 subsequences xs = [] : nonEmptySubsequences xs
783
784 -- | The 'nonEmptySubsequences' function returns the list of all subsequences of the argument,
785 -- except for the empty list.
786 --
787 -- > nonEmptySubsequences "abc" == ["a","b","ab","c","ac","bc","abc"]
788 nonEmptySubsequences :: [a] -> [[a]]
789 nonEmptySubsequences [] = []
790 nonEmptySubsequences (x:xs) = [x] : foldr f [] (nonEmptySubsequences xs)
791 where f ys r = ys : (x : ys) : r
792
793
794 -- | The 'permutations' function returns the list of all permutations of the argument.
795 --
796 -- > permutations "abc" == ["abc","bac","cba","bca","cab","acb"]
797 permutations :: [a] -> [[a]]
798 permutations xs0 = xs0 : perms xs0 []
799 where
800 perms [] _ = []
801 perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)
802 where interleave xs r = let (_,zs) = interleave' id xs r in zs
803 interleave' _ [] r = (ts, r)
804 interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r
805 in (y:us, f (t:y:us) : zs)
806
807
808 ------------------------------------------------------------------------------
809 -- Quick Sort algorithm taken from HBC's QSort library.
810
811 -- | The 'sort' function implements a stable sorting algorithm.
812 -- It is a special case of 'sortBy', which allows the programmer to supply
813 -- their own comparison function.
814 sort :: (Ord a) => [a] -> [a]
815
816 -- | The 'sortBy' function is the non-overloaded version of 'sort'.
817 sortBy :: (a -> a -> Ordering) -> [a] -> [a]
818
819 #ifdef USE_REPORT_PRELUDE
820 sort = sortBy compare
821 sortBy cmp = foldr (insertBy cmp) []
822 #else
823
824 {-
825 GHC's mergesort replaced by a better implementation, 24/12/2009.
826 This code originally contributed to the nhc12 compiler by Thomas Nordin
827 in 2002. Rumoured to have been based on code by Lennart Augustsson, e.g.
828 http://www.mail-archive.com/haskell@haskell.org/msg01822.html
829 and possibly to bear similarities to a 1982 paper by Richard O'Keefe:
830 "A smooth applicative merge sort".
831
832 Benchmarks show it to be often 2x the speed of the previous implementation.
833 Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/2143
834 -}
835
836 sort = sortBy compare
837 sortBy cmp = mergeAll . sequences
838 where
839 sequences (a:b:xs)
840 | a `cmp` b == GT = descending b [a] xs
841 | otherwise = ascending b (a:) xs
842 sequences xs = [xs]
843
844 descending a as (b:bs)
845 | a `cmp` b == GT = descending b (a:as) bs
846 descending a as bs = (a:as): sequences bs
847
848 ascending a as (b:bs)
849 | a `cmp` b /= GT = ascending b (\ys -> as (a:ys)) bs
850 ascending a as bs = as [a]: sequences bs
851
852 mergeAll [x] = x
853 mergeAll xs = mergeAll (mergePairs xs)
854
855 mergePairs (a:b:xs) = merge a b: mergePairs xs
856 mergePairs xs = xs
857
858 merge as@(a:as') bs@(b:bs')
859 | a `cmp` b == GT = b:merge as bs'
860 | otherwise = a:merge as' bs
861 merge [] bs = bs
862 merge as [] = as
863
864 {-
865 sortBy cmp l = mergesort cmp l
866 sort l = mergesort compare l
867
868 Quicksort replaced by mergesort, 14/5/2002.
869
870 From: Ian Lynagh <igloo@earth.li>
871
872 I am curious as to why the List.sort implementation in GHC is a
873 quicksort algorithm rather than an algorithm that guarantees n log n
874 time in the worst case? I have attached a mergesort implementation along
875 with a few scripts to time it's performance, the results of which are
876 shown below (* means it didn't finish successfully - in all cases this
877 was due to a stack overflow).
878
879 If I heap profile the random_list case with only 10000 then I see
880 random_list peaks at using about 2.5M of memory, whereas in the same
881 program using List.sort it uses only 100k.
882
883 Input style Input length Sort data Sort alg User time
884 stdin 10000 random_list sort 2.82
885 stdin 10000 random_list mergesort 2.96
886 stdin 10000 sorted sort 31.37
887 stdin 10000 sorted mergesort 1.90
888 stdin 10000 revsorted sort 31.21
889 stdin 10000 revsorted mergesort 1.88
890 stdin 100000 random_list sort *
891 stdin 100000 random_list mergesort *
892 stdin 100000 sorted sort *
893 stdin 100000 sorted mergesort *
894 stdin 100000 revsorted sort *
895 stdin 100000 revsorted mergesort *
896 func 10000 random_list sort 0.31
897 func 10000 random_list mergesort 0.91
898 func 10000 sorted sort 19.09
899 func 10000 sorted mergesort 0.15
900 func 10000 revsorted sort 19.17
901 func 10000 revsorted mergesort 0.16
902 func 100000 random_list sort 3.85
903 func 100000 random_list mergesort *
904 func 100000 sorted sort 5831.47
905 func 100000 sorted mergesort 2.23
906 func 100000 revsorted sort 5872.34
907 func 100000 revsorted mergesort 2.24
908
909 mergesort :: (a -> a -> Ordering) -> [a] -> [a]
910 mergesort cmp = mergesort' cmp . map wrap
911
912 mergesort' :: (a -> a -> Ordering) -> [[a]] -> [a]
913 mergesort' _ [] = []
914 mergesort' _ [xs] = xs
915 mergesort' cmp xss = mergesort' cmp (merge_pairs cmp xss)
916
917 merge_pairs :: (a -> a -> Ordering) -> [[a]] -> [[a]]
918 merge_pairs _ [] = []
919 merge_pairs _ [xs] = [xs]
920 merge_pairs cmp (xs:ys:xss) = merge cmp xs ys : merge_pairs cmp xss
921
922 merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
923 merge _ [] ys = ys
924 merge _ xs [] = xs
925 merge cmp (x:xs) (y:ys)
926 = case x `cmp` y of
927 GT -> y : merge cmp (x:xs) ys
928 _ -> x : merge cmp xs (y:ys)
929
930 wrap :: a -> [a]
931 wrap x = [x]
932
933
934
935 OLDER: qsort version
936
937 -- qsort is stable and does not concatenate.
938 qsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
939 qsort _ [] r = r
940 qsort _ [x] r = x:r
941 qsort cmp (x:xs) r = qpart cmp x xs [] [] r
942
943 -- qpart partitions and sorts the sublists
944 qpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]
945 qpart cmp x [] rlt rge r =
946 -- rlt and rge are in reverse order and must be sorted with an
947 -- anti-stable sorting
948 rqsort cmp rlt (x:rqsort cmp rge r)
949 qpart cmp x (y:ys) rlt rge r =
950 case cmp x y of
951 GT -> qpart cmp x ys (y:rlt) rge r
952 _ -> qpart cmp x ys rlt (y:rge) r
953
954 -- rqsort is as qsort but anti-stable, i.e. reverses equal elements
955 rqsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
956 rqsort _ [] r = r
957 rqsort _ [x] r = x:r
958 rqsort cmp (x:xs) r = rqpart cmp x xs [] [] r
959
960 rqpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]
961 rqpart cmp x [] rle rgt r =
962 qsort cmp rle (x:qsort cmp rgt r)
963 rqpart cmp x (y:ys) rle rgt r =
964 case cmp y x of
965 GT -> rqpart cmp x ys rle (y:rgt) r
966 _ -> rqpart cmp x ys (y:rle) rgt r
967 -}
968
969 #endif /* USE_REPORT_PRELUDE */
970
971 -- | Sort a list by comparing the results of a key function applied to each
972 -- element. @sortOn f@ is equivalent to @sortBy . comparing f@, but has the
973 -- performance advantage of only evaluating @f@ once for each element in the
974 -- input list. This is called the decorate-sort-undecorate paradigm, or
975 -- Schwartzian transform.
976 --
977 -- @since 4.8.0.0
978 sortOn :: Ord b => (a -> b) -> [a] -> [a]
979 sortOn f =
980 map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))
981
982 -- | The 'unfoldr' function is a \`dual\' to 'foldr': while 'foldr'
983 -- reduces a list to a summary value, 'unfoldr' builds a list from
984 -- a seed value. The function takes the element and returns 'Nothing'
985 -- if it is done producing the list or returns 'Just' @(a,b)@, in which
986 -- case, @a@ is a prepended to the list and @b@ is used as the next
987 -- element in a recursive call. For example,
988 --
989 -- > iterate f == unfoldr (\x -> Just (x, f x))
990 --
991 -- In some cases, 'unfoldr' can undo a 'foldr' operation:
992 --
993 -- > unfoldr f' (foldr f z xs) == xs
994 --
995 -- if the following holds:
996 --
997 -- > f' (f x y) = Just (x,y)
998 -- > f' z = Nothing
999 --
1000 -- A simple use of unfoldr:
1001 --
1002 -- > unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
1003 -- > [10,9,8,7,6,5,4,3,2,1]
1004 --
1005
1006 -- Note [INLINE unfoldr]
1007 -- We treat unfoldr a little differently from some other forms for list fusion
1008 -- for two reasons:
1009 --
1010 -- 1. We don't want to use a rule to rewrite a basic form to a fusible
1011 -- form because this would inline before constant floating. As Simon Peyton-
1012 -- Jones and others have pointed out, this could reduce sharing in some cases
1013 -- where sharing is beneficial. Thus we simply INLINE it, which is, for
1014 -- example, how enumFromTo::Int becomes eftInt. Unfortunately, we don't seem
1015 -- to get enough of an inlining discount to get a version of eftInt based on
1016 -- unfoldr to inline as readily as the usual one. We know that all the Maybe
1017 -- nonsense will go away, but the compiler does not.
1018 --
1019 -- 2. The benefit of inlining unfoldr is likely to be huge in many common cases,
1020 -- even apart from list fusion. In particular, inlining unfoldr often
1021 -- allows GHC to erase all the Maybes. This appears to be critical if unfoldr
1022 -- is to be used in high-performance code. A small increase in code size
1023 -- in the relatively rare cases when this does not happen looks like a very
1024 -- small price to pay.
1025 --
1026 -- Doing a back-and-forth dance doesn't seem to accomplish anything if the
1027 -- final form has to be inlined in any case.
1028
1029 unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
1030
1031 {-# INLINE unfoldr #-} -- See Note [INLINE unfoldr]
1032 unfoldr f b0 = build (\c n ->
1033 let go b = case f b of
1034 Just (a, new_b) -> a `c` go new_b
1035 Nothing -> n
1036 in go b0)
1037
1038 -- -----------------------------------------------------------------------------
1039 -- Functions on strings
1040
1041 -- | 'lines' breaks a string up into a list of strings at newline
1042 -- characters. The resulting strings do not contain newlines.
1043 lines :: String -> [String]
1044 lines "" = []
1045 -- Somehow GHC doesn't detect the selector thunks in the below code,
1046 -- so s' keeps a reference to the first line via the pair and we have
1047 -- a space leak (cf. #4334).
1048 -- So we need to make GHC see the selector thunks with a trick.
1049 lines s = cons (case break (== '\n') s of
1050 (l, s') -> (l, case s' of
1051 [] -> []
1052 _:s'' -> lines s''))
1053 where
1054 cons ~(h, t) = h : t
1055
1056 -- | 'unlines' is an inverse operation to 'lines'.
1057 -- It joins lines, after appending a terminating newline to each.
1058 unlines :: [String] -> String
1059 #ifdef USE_REPORT_PRELUDE
1060 unlines = concatMap (++ "\n")
1061 #else
1062 -- HBC version (stolen)
1063 -- here's a more efficient version
1064 unlines [] = []
1065 unlines (l:ls) = l ++ '\n' : unlines ls
1066 #endif
1067
1068 -- | 'words' breaks a string up into a list of words, which were delimited
1069 -- by white space.
1070 words :: String -> [String]
1071 {-# NOINLINE [1] words #-}
1072 words s = case dropWhile {-partain:Char.-}isSpace s of
1073 "" -> []
1074 s' -> w : words s''
1075 where (w, s'') =
1076 break {-partain:Char.-}isSpace s'
1077
1078 {-# RULES
1079 "words" [~1] forall s . words s = build (\c n -> wordsFB c n s)
1080 "wordsList" [1] wordsFB (:) [] = words
1081 #-}
1082 wordsFB :: ([Char] -> b -> b) -> b -> String -> b
1083 {-# NOINLINE [0] wordsFB #-}
1084 wordsFB c n = go
1085 where
1086 go s = case dropWhile isSpace s of
1087 "" -> n
1088 s' -> w `c` go s''
1089 where (w, s'') = break isSpace s'
1090
1091 -- | 'unwords' is an inverse operation to 'words'.
1092 -- It joins words with separating spaces.
1093 unwords :: [String] -> String
1094 #ifdef USE_REPORT_PRELUDE
1095 unwords [] = ""
1096 unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
1097 #else
1098 -- Here's a lazier version that can get the last element of a
1099 -- _|_-terminated list.
1100 {-# NOINLINE [1] unwords #-}
1101 unwords [] = ""
1102 unwords (w:ws) = w ++ go ws
1103 where
1104 go [] = ""
1105 go (v:vs) = ' ' : (v ++ go vs)
1106
1107 -- In general, the foldr-based version is probably slightly worse
1108 -- than the HBC version, because it adds an extra space and then takes
1109 -- it back off again. But when it fuses, it reduces allocation. How much
1110 -- depends entirely on the average word length--it's most effective when
1111 -- the words are on the short side.
1112 {-# RULES
1113 "unwords" [~1] forall ws .
1114 unwords ws = tailUnwords (foldr unwordsFB "" ws)
1115 "unwordsList" [1] forall ws .
1116 tailUnwords (foldr unwordsFB "" ws) = unwords ws
1117 #-}
1118
1119 {-# INLINE [0] tailUnwords #-}
1120 tailUnwords :: String -> String
1121 tailUnwords [] = []
1122 tailUnwords (_:xs) = xs
1123
1124 {-# INLINE [0] unwordsFB #-}
1125 unwordsFB :: String -> String -> String
1126 unwordsFB w r = ' ' : w ++ r
1127 #endif
1128
1129 {- A "SnocBuilder" is a version of Chris Okasaki's banker's queue that supports
1130 toListSB instead of uncons. In single-threaded use, its performance
1131 characteristics are similar to John Hughes's functional difference lists, but
1132 likely somewhat worse. In heavily persistent settings, however, it does much
1133 better, because it takes advantage of sharing. The banker's queue guarantees
1134 (amortized) O(1) snoc and O(1) uncons, meaning that we can think of toListSB as
1135 an O(1) conversion to a list-like structure a constant factor slower than
1136 normal lists--we pay the O(n) cost incrementally as we consume the list. Using
1137 functional difference lists, on the other hand, we would have to pay the whole
1138 cost up front for each output list. -}
1139
1140 {- We store a front list, a rear list, and the length of the queue. Because we
1141 only snoc onto the queue and never uncons, we know it's time to rotate when the
1142 length of the queue plus 1 is a power of 2. Note that we rely on the value of
1143 the length field only for performance. In the unlikely event of overflow, the
1144 performance will suffer but the semantics will remain correct. -}
1145
1146 data SnocBuilder a = SnocBuilder {-# UNPACK #-} !Word [a] [a]
1147
1148 {- Smart constructor that rotates the builder when lp is one minus a power of
1149 2. Does not rotate very small builders because doing so is not worth the
1150 trouble. The lp < 255 test goes first because the power-of-2 test gives awful
1151 branch prediction for very small n (there are 5 powers of 2 between 1 and
1152 16). Putting the well-predicted lp < 255 test first avoids branching on the
1153 power-of-2 test until powers of 2 have become sufficiently rare to be predicted
1154 well. -}
1155
1156 {-# INLINE sb #-}
1157 sb :: Word -> [a] -> [a] -> SnocBuilder a
1158 sb lp f r
1159 | lp < 255 || (lp .&. (lp + 1)) /= 0 = SnocBuilder lp f r
1160 | otherwise = SnocBuilder lp (f ++ reverse r) []
1161
1162 -- The empty builder
1163
1164 emptySB :: SnocBuilder a
1165 emptySB = SnocBuilder 0 [] []
1166
1167 -- Add an element to the end of a queue.
1168
1169 snocSB :: SnocBuilder a -> a -> SnocBuilder a
1170 snocSB (SnocBuilder lp f r) x = sb (lp + 1) f (x:r)
1171
1172 -- Convert a builder to a list
1173
1174 toListSB :: SnocBuilder a -> [a]
1175 toListSB (SnocBuilder _ f r) = f ++ reverse r