2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- The List data type and its operations
15 -----------------------------------------------------------------------------
19 -- [] (..), -- Not Haskell 98; built in syntax
21 map, (++), filter, concat,
22 head, last, tail, init, null, length, (!!),
23 foldl, scanl, scanl1, foldr, foldr1, scanr, scanr1,
24 iterate, repeat, replicate, cycle,
25 take, drop, splitAt, takeWhile, dropWhile, span, break,
27 any, all, elem, notElem, lookup,
29 zip, zip3, zipWith, zipWith3, unzip, unzip3,
32 #ifndef USE_REPORT_PRELUDE
33 -- non-standard, but hidden when creating the Prelude
40 import {-# SOURCE #-} GHC.Err ( error )
46 infix 4 `elem`, `notElem`
49 %*********************************************************
51 \subsection{List-manipulation functions}
53 %*********************************************************
56 -- | Extract the first element of a list, which must be non-empty.
61 badHead = errorEmptyList "head"
63 -- This rule is useful in cases like
64 -- head [y | (x,y) <- ps, x==t]
66 "head/build" forall (g::forall b.(Bool->b->b)->b->b) .
67 head (build g) = g (\x _ -> x) badHead
68 "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
69 head (augment g xs) = g (\x _ -> x) (head xs)
72 -- | Extract the elements after the head of a list, which must be non-empty.
75 tail [] = errorEmptyList "tail"
77 -- | Extract the last element of a list, which must be finite and non-empty.
79 #ifdef USE_REPORT_PRELUDE
82 last [] = errorEmptyList "last"
84 -- eliminate repeated cases
85 last [] = errorEmptyList "last"
86 last (x:xs) = last' x xs
88 last' _ (y:ys) = last' y ys
91 -- | Return all the elements of a list except the last one.
92 -- The list must be finite and non-empty.
94 #ifdef USE_REPORT_PRELUDE
96 init (x:xs) = x : init xs
97 init [] = errorEmptyList "init"
99 -- eliminate repeated cases
100 init [] = errorEmptyList "init"
101 init (x:xs) = init' x xs
102 where init' _ [] = []
103 init' y (z:zs) = y : init' z zs
106 -- | Test whether a list is empty.
111 -- | 'length' returns the length of a finite list as an 'Int'.
112 -- It is an instance of the more general 'Data.List.genericLength',
113 -- the result type of which may be any kind of number.
117 len :: [a] -> Int# -> Int
119 len (_:xs) a# = len xs (a# +# 1#)
121 -- | 'filter', applied to a predicate and a list, returns the list of
122 -- those elements that satisfy the predicate; i.e.,
124 -- > filter p xs = [ x | x <- xs, p x]
126 filter :: (a -> Bool) -> [a] -> [a]
129 | pred x = x : filter pred xs
130 | otherwise = filter pred xs
132 {-# NOINLINE [0] filterFB #-}
133 filterFB c p x r | p x = x `c` r
137 "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
138 "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
139 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
142 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
143 -- filterFB (filterFB c p) q a b
144 -- = if q a then filterFB c p a b else b
145 -- = if q a then (if p a then c a b else b) else b
146 -- = if q a && p a then c a b else b
147 -- = filterFB c (\x -> q x && p x) a b
148 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
149 -- gave rise to a live bug report. SLPJ.
152 -- | 'foldl', applied to a binary operator, a starting value (typically
153 -- the left-identity of the operator), and a list, reduces the list
154 -- using the binary operator, from left to right:
156 -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
158 -- The list must be finite.
160 -- We write foldl as a non-recursive thing, so that it
161 -- can be inlined, and then (often) strictness-analysed,
162 -- and hence the classic space leak on foldl (+) 0 xs
164 foldl :: (a -> b -> a) -> a -> [b] -> a
165 foldl f z xs = lgo z xs
168 lgo z (x:xs) = lgo (f z x) xs
170 -- | 'scanl' is similar to 'foldl', but returns a list of successive
171 -- reduced values from the left:
173 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
177 -- > last (scanl f z xs) == foldl f z xs.
179 scanl :: (a -> b -> a) -> a -> [b] -> [a]
180 scanl f q ls = q : (case ls of
182 x:xs -> scanl f (f q x) xs)
184 -- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
186 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
188 scanl1 :: (a -> a -> a) -> [a] -> [a]
189 scanl1 f (x:xs) = scanl f x xs
192 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
195 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
196 -- and thus must be applied to non-empty lists.
198 foldr1 :: (a -> a -> a) -> [a] -> a
200 foldr1 f (x:xs) = f x (foldr1 f xs)
201 foldr1 _ [] = errorEmptyList "foldr1"
203 -- | 'scanr' is the right-to-left dual of 'scanl'.
206 -- > head (scanr f z xs) == foldr f z xs.
208 scanr :: (a -> b -> b) -> b -> [a] -> [b]
210 scanr f q0 (x:xs) = f x q : qs
211 where qs@(q:_) = scanr f q0 xs
213 -- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
215 scanr1 :: (a -> a -> a) -> [a] -> [a]
218 scanr1 f (x:xs) = f x q : qs
219 where qs@(q:_) = scanr1 f xs
221 -- | 'iterate' @f x@ returns an infinite list of repeated applications
224 -- > iterate f x == [x, f x, f (f x), ...]
226 iterate :: (a -> a) -> a -> [a]
227 iterate f x = x : iterate f (f x)
229 iterateFB c f x = x `c` iterateFB c f (f x)
233 "iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
234 "iterateFB" [1] iterateFB (:) = iterate
238 -- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
240 {-# INLINE [0] repeat #-}
241 -- The pragma just gives the rules more chance to fire
242 repeat x = xs where xs = x : xs
244 {-# INLINE [0] repeatFB #-} -- ditto
245 repeatFB c x = xs where xs = x `c` xs
249 "repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
250 "repeatFB" [1] repeatFB (:) = repeat
253 -- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
255 -- It is an instance of the more general 'Data.List.genericReplicate',
256 -- in which @n@ may be of any integral type.
257 replicate :: Int -> a -> [a]
258 replicate n x = take n (repeat x)
260 -- | 'cycle' ties a finite list into a circular one, or equivalently,
261 -- the infinite repetition of the original list. It is the identity
262 -- on infinite lists.
265 cycle [] = error "Prelude.cycle: empty list"
266 cycle xs = xs' where xs' = xs ++ xs'
268 -- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
269 -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@.
271 takeWhile :: (a -> Bool) -> [a] -> [a]
274 | p x = x : takeWhile p xs
277 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
279 dropWhile :: (a -> Bool) -> [a] -> [a]
281 dropWhile p xs@(x:xs')
282 | p x = dropWhile p xs'
285 -- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
286 -- of length @n@, or @xs@ itself if @n > 'length' xs@.
287 -- It is an instance of the more general 'Data.List.genericTake',
288 -- in which @n@ may be of any integral type.
289 take :: Int -> [a] -> [a]
291 -- | 'drop' @n xs@ returns the suffix of @xs@
292 -- after the first @n@ elements, or @[]@ if @n > 'length' xs@.
293 -- It is an instance of the more general 'Data.List.genericDrop',
294 -- in which @n@ may be of any integral type.
295 drop :: Int -> [a] -> [a]
297 -- | 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
298 -- It is an instance of the more general 'Data.List.genericSplitAt',
299 -- in which @n@ may be of any integral type.
300 splitAt :: Int -> [a] -> ([a],[a])
302 #ifdef USE_REPORT_PRELUDE
303 take n _ | n <= 0 = []
305 take n (x:xs) = x : take (n-1) xs
307 drop n xs | n <= 0 = xs
309 drop n (_:xs) = drop (n-1) xs
311 splitAt n xs = (take n xs, drop n xs)
313 #else /* hack away */
314 take (I# n#) xs = takeUInt n# xs
316 -- The general code for take, below, checks n <= maxInt
317 -- No need to check for maxInt overflow when specialised
318 -- at type Int or Int# since the Int must be <= maxInt
320 takeUInt :: Int# -> [b] -> [b]
322 | n >=# 0# = take_unsafe_UInt n xs
325 take_unsafe_UInt :: Int# -> [b] -> [b]
326 take_unsafe_UInt 0# _ = []
327 take_unsafe_UInt m ls =
330 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
332 takeUInt_append :: Int# -> [b] -> [b] -> [b]
333 takeUInt_append n xs rs
334 | n >=# 0# = take_unsafe_UInt_append n xs rs
337 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
338 take_unsafe_UInt_append 0# _ rs = rs
339 take_unsafe_UInt_append m ls rs =
342 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
346 | otherwise = drop# n# ls
348 drop# :: Int# -> [a] -> [a]
351 drop# m# (_:xs) = drop# (m# -# 1#) xs
354 | n# <# 0# = ([], ls)
355 | otherwise = splitAt# n# ls
357 splitAt# :: Int# -> [a] -> ([a], [a])
358 splitAt# 0# xs = ([], xs)
359 splitAt# _ xs@[] = (xs, xs)
360 splitAt# m# (x:xs) = (x:xs', xs'')
362 (xs', xs'') = splitAt# (m# -# 1#) xs
364 #endif /* USE_REPORT_PRELUDE */
366 -- | 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
368 span :: (a -> Bool) -> [a] -> ([a],[a])
369 span _ xs@[] = (xs, xs)
371 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
372 | otherwise = ([],xs)
374 -- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
376 break :: (a -> Bool) -> [a] -> ([a],[a])
377 #ifdef USE_REPORT_PRELUDE
378 break p = span (not . p)
380 -- HBC version (stolen)
381 break _ xs@[] = (xs, xs)
384 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
387 -- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
388 -- @xs@ must be finite.
389 reverse :: [a] -> [a]
390 #ifdef USE_REPORT_PRELUDE
391 reverse = foldl (flip (:)) []
396 rev (x:xs) a = rev xs (x:a)
399 -- | 'and' returns the conjunction of a Boolean list. For the result to be
400 -- 'True', the list must be finite; 'False', however, results from a 'False'
401 -- value at a finite index of a finite or infinite list.
402 and :: [Bool] -> Bool
404 -- | 'or' returns the disjunction of a Boolean list. For the result to be
405 -- 'False', the list must be finite; 'True', however, results from a 'True'
406 -- value at a finite index of a finite or infinite list.
408 #ifdef USE_REPORT_PRELUDE
409 and = foldr (&&) True
410 or = foldr (||) False
413 and (x:xs) = x && and xs
415 or (x:xs) = x || or xs
418 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
419 and (build g) = g (&&) True
420 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
421 or (build g) = g (||) False
425 -- | Applied to a predicate and a list, 'any' determines if any element
426 -- of the list satisfies the predicate.
427 any :: (a -> Bool) -> [a] -> Bool
429 -- | Applied to a predicate and a list, 'all' determines if all elements
430 -- of the list satisfy the predicate.
431 all :: (a -> Bool) -> [a] -> Bool
432 #ifdef USE_REPORT_PRELUDE
437 any p (x:xs) = p x || any p xs
440 all p (x:xs) = p x && all p xs
442 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
443 any p (build g) = g ((||) . p) False
444 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
445 all p (build g) = g ((&&) . p) True
449 -- | 'elem' is the list membership predicate, usually written in infix form,
450 -- e.g., @x `elem` xs@.
451 elem :: (Eq a) => a -> [a] -> Bool
453 -- | 'notElem' is the negation of 'elem'.
454 notElem :: (Eq a) => a -> [a] -> Bool
455 #ifdef USE_REPORT_PRELUDE
457 notElem x = all (/= x)
460 elem x (y:ys) = x==y || elem x ys
463 notElem x (y:ys)= x /= y && notElem x ys
466 -- | 'lookup' @key assocs@ looks up a key in an association list.
467 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
468 lookup _key [] = Nothing
469 lookup key ((x,y):xys)
471 | otherwise = lookup key xys
473 -- | Map a function over a list and concatenate the results.
474 concatMap :: (a -> [b]) -> [a] -> [b]
475 concatMap f = foldr ((++) . f) []
477 -- | Concatenate a list of lists.
478 concat :: [[a]] -> [a]
479 concat = foldr (++) []
482 "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
483 -- We don't bother to turn non-fusible applications of concat back into concat
490 -- | List index (subscript) operator, starting from 0.
491 -- It is an instance of the more general 'Data.List.genericIndex',
492 -- which takes an index of any integral type.
493 (!!) :: [a] -> Int -> a
494 #ifdef USE_REPORT_PRELUDE
495 xs !! n | n < 0 = error "Prelude.!!: negative index"
496 [] !! _ = error "Prelude.!!: index too large"
498 (_:xs) !! n = xs !! (n-1)
500 -- HBC version (stolen), then unboxified
501 -- The semantics is not quite the same for error conditions
502 -- in the more efficient version.
504 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
505 | otherwise = sub xs n
507 sub :: [a] -> Int# -> a
508 sub [] _ = error "Prelude.(!!): index too large\n"
509 sub (y:ys) n = if n ==# 0#
511 else sub ys (n -# 1#)
516 %*********************************************************
518 \subsection{The zip family}
520 %*********************************************************
523 foldr2 _k z [] _ys = z
524 foldr2 _k z _xs [] = z
525 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
527 foldr2_left _k z _x _r [] = z
528 foldr2_left k _z x r (y:ys) = k x y (r ys)
530 foldr2_right _k z _y _r [] = z
531 foldr2_right k _z y r (x:xs) = k x y (r xs)
533 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
534 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
536 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
537 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
539 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
540 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
544 The foldr2/right rule isn't exactly right, because it changes
545 the strictness of foldr2 (and thereby zip)
547 E.g. main = print (null (zip nonobviousNil (build undefined)))
548 where nonobviousNil = f 3
549 f n = if n == 0 then [] else f (n-1)
551 I'm going to leave it though.
554 Zips for larger tuples are in the List module.
557 ----------------------------------------------
558 -- | 'zip' takes two lists and returns a list of corresponding pairs.
559 -- If one input list is short, excess elements of the longer list are
561 zip :: [a] -> [b] -> [(a,b)]
562 zip (a:as) (b:bs) = (a,b) : zip as bs
565 {-# INLINE [0] zipFB #-}
566 zipFB c x y r = (x,y) `c` r
569 "zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
570 "zipList" [1] foldr2 (zipFB (:)) [] = zip
575 ----------------------------------------------
576 -- | 'zip3' takes three lists and returns a list of triples, analogous to
578 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
580 -- zip3 = zipWith3 (,,)
581 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
586 -- The zipWith family generalises the zip family by zipping with the
587 -- function given as the first argument, instead of a tupling function.
590 ----------------------------------------------
591 -- | 'zipWith' generalises 'zip' by zipping with the function given
592 -- as the first argument, instead of a tupling function.
593 -- For example, @'zipWith' (+)@ is applied to two lists to produce the
594 -- list of corresponding sums.
595 zipWith :: (a->b->c) -> [a]->[b]->[c]
596 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
599 {-# INLINE [0] zipWithFB #-}
600 zipWithFB c f x y r = (x `f` y) `c` r
603 "zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
604 "zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
609 -- | The 'zipWith3' function takes a function which combines three
610 -- elements, as well as three lists and returns a list of their point-wise
611 -- combination, analogous to 'zipWith'.
612 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
613 zipWith3 z (a:as) (b:bs) (c:cs)
614 = z a b c : zipWith3 z as bs cs
615 zipWith3 _ _ _ _ = []
617 -- | 'unzip' transforms a list of pairs into a list of first components
618 -- and a list of second components.
619 unzip :: [(a,b)] -> ([a],[b])
621 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
623 -- | The 'unzip3' function takes a list of triples and returns three
624 -- lists, analogous to 'unzip'.
625 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
626 {-# INLINE unzip3 #-}
627 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
632 %*********************************************************
634 \subsection{Error code}
636 %*********************************************************
638 Common up near identical calls to `error' to reduce the number
639 constant strings created when compiled:
642 errorEmptyList :: String -> a
644 error (prel_list_str ++ fun ++ ": empty list")
646 prel_list_str :: String
647 prel_list_str = "Prelude."