2 {-# OPTIONS -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 -----------------------------------------------------------------------------
18 -- [] (..), -- Not Haskell 98; built in syntax
20 map, (++), filter, concat,
21 head, last, tail, init, null, length, (!!),
22 foldl, scanl, scanl1, foldr, foldr1, scanr, scanr1,
23 iterate, repeat, replicate, cycle,
24 take, drop, splitAt, takeWhile, dropWhile, span, break,
26 any, all, elem, notElem, lookup,
28 zip, zip3, zipWith, zipWith3, unzip, unzip3,
31 #ifndef USE_REPORT_PRELUDE
32 -- non-standard, but hidden when creating the Prelude
39 import {-# SOURCE #-} GHC.Err ( error )
45 infix 4 `elem`, `notElem`
48 %*********************************************************
50 \subsection{List-manipulation functions}
52 %*********************************************************
55 -- | Extract the first element of a list, which must be non-empty.
60 badHead = errorEmptyList "head"
62 -- This rule is useful in cases like
63 -- head [y | (x,y) <- ps, x==t]
65 "head/build" forall (g::forall b.(Bool->b->b)->b->b) .
66 head (build g) = g (\x _ -> x) badHead
67 "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
68 head (augment g xs) = g (\x _ -> x) (head xs)
71 -- | Extract the elements after the head of a list, which must be non-empty.
74 tail [] = errorEmptyList "tail"
76 -- | Extract the last element of a list, which must be finite and non-empty.
78 #ifdef USE_REPORT_PRELUDE
81 last [] = errorEmptyList "last"
83 -- eliminate repeated cases
84 last [] = errorEmptyList "last"
85 last (x:xs) = last' x xs
87 last' _ (y:ys) = last' y ys
90 -- | Return all the elements of a list except the last one.
91 -- The list must be finite and non-empty.
93 #ifdef USE_REPORT_PRELUDE
95 init (x:xs) = x : init xs
96 init [] = errorEmptyList "init"
98 -- eliminate repeated cases
99 init [] = errorEmptyList "init"
100 init (x:xs) = init' x xs
101 where init' _ [] = []
102 init' y (z:zs) = y : init' z zs
105 -- | Test whether a list is empty.
110 -- | 'length' returns the length of a finite list as an 'Int'.
111 -- It is an instance of the more general 'Data.List.genericLength',
112 -- the result type of which may be any kind of number.
116 len :: [a] -> Int# -> Int
118 len (_:xs) a# = len xs (a# +# 1#)
120 -- | 'filter', applied to a predicate and a list, returns the list of
121 -- those elements that satisfy the predicate; i.e.,
123 -- > filter p xs = [ x | x <- xs, p x]
125 filter :: (a -> Bool) -> [a] -> [a]
128 | pred x = x : filter pred xs
129 | otherwise = filter pred xs
131 {-# NOINLINE [0] filterFB #-}
132 filterFB c p x r | p x = x `c` r
136 "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
137 "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
138 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
141 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
142 -- filterFB (filterFB c p) q a b
143 -- = if q a then filterFB c p a b else b
144 -- = if q a then (if p a then c a b else b) else b
145 -- = if q a && p a then c a b else b
146 -- = filterFB c (\x -> q x && p x) a b
147 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
148 -- gave rise to a live bug report. SLPJ.
151 -- | 'foldl', applied to a binary operator, a starting value (typically
152 -- the left-identity of the operator), and a list, reduces the list
153 -- using the binary operator, from left to right:
155 -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
157 -- The list must be finite.
159 -- We write foldl as a non-recursive thing, so that it
160 -- can be inlined, and then (often) strictness-analysed,
161 -- and hence the classic space leak on foldl (+) 0 xs
163 foldl :: (a -> b -> a) -> a -> [b] -> a
164 foldl f z xs = lgo z xs
167 lgo z (x:xs) = lgo (f z x) xs
169 -- | 'scanl' is similar to 'foldl', but returns a list of successive
170 -- reduced values from the left:
172 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
176 -- > last (scanl f z xs) == foldl f z xs.
178 scanl :: (a -> b -> a) -> a -> [b] -> [a]
179 scanl f q ls = q : (case ls of
181 x:xs -> scanl f (f q x) xs)
183 -- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
185 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
187 scanl1 :: (a -> a -> a) -> [a] -> [a]
188 scanl1 f (x:xs) = scanl f x xs
191 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
194 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
195 -- and thus must be applied to non-empty lists.
197 foldr1 :: (a -> a -> a) -> [a] -> a
199 foldr1 f (x:xs) = f x (foldr1 f xs)
200 foldr1 _ [] = errorEmptyList "foldr1"
202 -- | 'scanr' is the right-to-left dual of 'scanl'.
205 -- > head (scanr f z xs) == foldr f z xs.
207 scanr :: (a -> b -> b) -> b -> [a] -> [b]
209 scanr f q0 (x:xs) = f x q : qs
210 where qs@(q:_) = scanr f q0 xs
212 -- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
214 scanr1 :: (a -> a -> a) -> [a] -> [a]
217 scanr1 f (x:xs) = f x q : qs
218 where qs@(q:_) = scanr1 f xs
220 -- | 'iterate' @f x@ returns an infinite list of repeated applications
223 -- > iterate f x == [x, f x, f (f x), ...]
225 iterate :: (a -> a) -> a -> [a]
226 iterate f x = x : iterate f (f x)
228 iterateFB c f x = x `c` iterateFB c f (f x)
232 "iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
233 "iterateFB" [1] iterateFB (:) = iterate
237 -- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
239 {-# INLINE [0] repeat #-}
240 -- The pragma just gives the rules more chance to fire
241 repeat x = xs where xs = x : xs
243 {-# INLINE [0] repeatFB #-} -- ditto
244 repeatFB c x = xs where xs = x `c` xs
248 "repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
249 "repeatFB" [1] repeatFB (:) = repeat
252 -- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
254 -- It is an instance of the more general 'Data.List.genericReplicate',
255 -- in which @n@ may be of any integral type.
256 replicate :: Int -> a -> [a]
257 replicate n x = take n (repeat x)
259 -- | 'cycle' ties a finite list into a circular one, or equivalently,
260 -- the infinite repetition of the original list. It is the identity
261 -- on infinite lists.
264 cycle [] = error "Prelude.cycle: empty list"
265 cycle xs = xs' where xs' = xs ++ xs'
267 -- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
268 -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@.
270 takeWhile :: (a -> Bool) -> [a] -> [a]
273 | p x = x : takeWhile p xs
276 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
278 dropWhile :: (a -> Bool) -> [a] -> [a]
280 dropWhile p xs@(x:xs')
281 | p x = dropWhile p xs'
284 -- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
285 -- of length @n@, or @xs@ itself if @n > 'length' xs@.
286 -- It is an instance of the more general 'Data.List.genericTake',
287 -- in which @n@ may be of any integral type.
288 take :: Int -> [a] -> [a]
290 -- | 'drop' @n xs@ returns the suffix of @xs@
291 -- after the first @n@ elements, or @[]@ if @n > 'length' xs@.
292 -- It is an instance of the more general 'Data.List.genericDrop',
293 -- in which @n@ may be of any integral type.
294 drop :: Int -> [a] -> [a]
296 -- | 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
297 -- It is an instance of the more general 'Data.List.genericSplitAt',
298 -- in which @n@ may be of any integral type.
299 splitAt :: Int -> [a] -> ([a],[a])
301 #ifdef USE_REPORT_PRELUDE
302 take n _ | n <= 0 = []
304 take n (x:xs) = x : take (n-1) xs
306 drop n xs | n <= 0 = xs
308 drop n (_:xs) = drop (n-1) xs
310 splitAt n xs = (take n xs, drop n xs)
312 #else /* hack away */
313 take (I# n#) xs = takeUInt n# xs
315 -- The general code for take, below, checks n <= maxInt
316 -- No need to check for maxInt overflow when specialised
317 -- at type Int or Int# since the Int must be <= maxInt
319 takeUInt :: Int# -> [b] -> [b]
321 | n >=# 0# = take_unsafe_UInt n xs
324 take_unsafe_UInt :: Int# -> [b] -> [b]
325 take_unsafe_UInt 0# _ = []
326 take_unsafe_UInt m ls =
329 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
331 takeUInt_append :: Int# -> [b] -> [b] -> [b]
332 takeUInt_append n xs rs
333 | n >=# 0# = take_unsafe_UInt_append n xs rs
336 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
337 take_unsafe_UInt_append 0# _ rs = rs
338 take_unsafe_UInt_append m ls rs =
341 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
345 | otherwise = drop# n# ls
347 drop# :: Int# -> [a] -> [a]
350 drop# m# (_:xs) = drop# (m# -# 1#) xs
353 | n# <# 0# = ([], ls)
354 | otherwise = splitAt# n# ls
356 splitAt# :: Int# -> [a] -> ([a], [a])
357 splitAt# 0# xs = ([], xs)
358 splitAt# _ xs@[] = (xs, xs)
359 splitAt# m# (x:xs) = (x:xs', xs'')
361 (xs', xs'') = splitAt# (m# -# 1#) xs
363 #endif /* USE_REPORT_PRELUDE */
365 -- | 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
367 span :: (a -> Bool) -> [a] -> ([a],[a])
368 span _ xs@[] = (xs, xs)
370 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
371 | otherwise = ([],xs)
373 -- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
375 break :: (a -> Bool) -> [a] -> ([a],[a])
376 #ifdef USE_REPORT_PRELUDE
377 break p = span (not . p)
379 -- HBC version (stolen)
380 break _ xs@[] = (xs, xs)
383 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
386 -- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
387 -- @xs@ must be finite.
388 reverse :: [a] -> [a]
389 #ifdef USE_REPORT_PRELUDE
390 reverse = foldl (flip (:)) []
395 rev (x:xs) a = rev xs (x:a)
398 -- | 'and' returns the conjunction of a Boolean list. For the result to be
399 -- 'True', the list must be finite; 'False', however, results from a 'False'
400 -- value at a finite index of a finite or infinite list.
401 and :: [Bool] -> Bool
403 -- | 'or' returns the disjunction of a Boolean list. For the result to be
404 -- 'False', the list must be finite; 'True', however, results from a 'True'
405 -- value at a finite index of a finite or infinite list.
407 #ifdef USE_REPORT_PRELUDE
408 and = foldr (&&) True
409 or = foldr (||) False
412 and (x:xs) = x && and xs
414 or (x:xs) = x || or xs
417 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
418 and (build g) = g (&&) True
419 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
420 or (build g) = g (||) False
424 -- | Applied to a predicate and a list, 'any' determines if any element
425 -- of the list satisfies the predicate.
426 any :: (a -> Bool) -> [a] -> Bool
428 -- | Applied to a predicate and a list, 'all' determines if all elements
429 -- of the list satisfy the predicate.
430 all :: (a -> Bool) -> [a] -> Bool
431 #ifdef USE_REPORT_PRELUDE
436 any p (x:xs) = p x || any p xs
439 all p (x:xs) = p x && all p xs
441 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
442 any p (build g) = g ((||) . p) False
443 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
444 all p (build g) = g ((&&) . p) True
448 -- | 'elem' is the list membership predicate, usually written in infix form,
449 -- e.g., @x `elem` xs@.
450 elem :: (Eq a) => a -> [a] -> Bool
452 -- | 'notElem' is the negation of 'elem'.
453 notElem :: (Eq a) => a -> [a] -> Bool
454 #ifdef USE_REPORT_PRELUDE
456 notElem x = all (/= x)
459 elem x (y:ys) = x==y || elem x ys
462 notElem x (y:ys)= x /= y && notElem x ys
465 -- | 'lookup' @key assocs@ looks up a key in an association list.
466 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
467 lookup _key [] = Nothing
468 lookup key ((x,y):xys)
470 | otherwise = lookup key xys
472 -- | Map a function over a list and concatenate the results.
473 concatMap :: (a -> [b]) -> [a] -> [b]
474 concatMap f = foldr ((++) . f) []
476 -- | Concatenate a list of lists.
477 concat :: [[a]] -> [a]
478 concat = foldr (++) []
481 "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
482 -- We don't bother to turn non-fusible applications of concat back into concat
489 -- | List index (subscript) operator, starting from 0.
490 -- It is an instance of the more general 'Data.List.genericIndex',
491 -- which takes an index of any integral type.
492 (!!) :: [a] -> Int -> a
493 #ifdef USE_REPORT_PRELUDE
494 xs !! n | n < 0 = error "Prelude.!!: negative index"
495 [] !! _ = error "Prelude.!!: index too large"
497 (_:xs) !! n = xs !! (n-1)
499 -- HBC version (stolen), then unboxified
500 -- The semantics is not quite the same for error conditions
501 -- in the more efficient version.
503 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
504 | otherwise = sub xs n
506 sub :: [a] -> Int# -> a
507 sub [] _ = error "Prelude.(!!): index too large\n"
508 sub (y:ys) n = if n ==# 0#
510 else sub ys (n -# 1#)
515 %*********************************************************
517 \subsection{The zip family}
519 %*********************************************************
522 foldr2 _k z [] _ys = z
523 foldr2 _k z _xs [] = z
524 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
526 foldr2_left _k z _x _r [] = z
527 foldr2_left k _z x r (y:ys) = k x y (r ys)
529 foldr2_right _k z _y _r [] = z
530 foldr2_right k _z y r (x:xs) = k x y (r xs)
532 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
533 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
535 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
536 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
538 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
539 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
543 The foldr2/right rule isn't exactly right, because it changes
544 the strictness of foldr2 (and thereby zip)
546 E.g. main = print (null (zip nonobviousNil (build undefined)))
547 where nonobviousNil = f 3
548 f n = if n == 0 then [] else f (n-1)
550 I'm going to leave it though.
553 Zips for larger tuples are in the List module.
556 ----------------------------------------------
557 -- | 'zip' takes two lists and returns a list of corresponding pairs.
558 -- If one input list is short, excess elements of the longer list are
560 zip :: [a] -> [b] -> [(a,b)]
561 zip (a:as) (b:bs) = (a,b) : zip as bs
564 {-# INLINE [0] zipFB #-}
565 zipFB c x y r = (x,y) `c` r
568 "zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
569 "zipList" [1] foldr2 (zipFB (:)) [] = zip
574 ----------------------------------------------
575 -- | 'zip3' takes three lists and returns a list of triples, analogous to
577 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
579 -- zip3 = zipWith3 (,,)
580 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
585 -- The zipWith family generalises the zip family by zipping with the
586 -- function given as the first argument, instead of a tupling function.
589 ----------------------------------------------
590 -- | 'zipWith' generalises 'zip' by zipping with the function given
591 -- as the first argument, instead of a tupling function.
592 -- For example, @'zipWith' (+)@ is applied to two lists to produce the
593 -- list of corresponding sums.
594 zipWith :: (a->b->c) -> [a]->[b]->[c]
595 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
598 {-# INLINE [0] zipWithFB #-}
599 zipWithFB c f x y r = (x `f` y) `c` r
602 "zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
603 "zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
608 -- | The 'zipWith3' function takes a function which combines three
609 -- elements, as well as three lists and returns a list of their point-wise
610 -- combination, analogous to 'zipWith'.
611 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
612 zipWith3 z (a:as) (b:bs) (c:cs)
613 = z a b c : zipWith3 z as bs cs
614 zipWith3 _ _ _ _ = []
616 -- | 'unzip' transforms a list of pairs into a list of first components
617 -- and a list of second components.
618 unzip :: [(a,b)] -> ([a],[b])
620 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
622 -- | The 'unzip3' function takes a list of triples and returns three
623 -- lists, analogous to 'unzip'.
624 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
625 {-# INLINE unzip3 #-}
626 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
631 %*********************************************************
633 \subsection{Error code}
635 %*********************************************************
637 Common up near identical calls to `error' to reduce the number
638 constant strings created when compiled:
641 errorEmptyList :: String -> a
643 error (prel_list_str ++ fun ++ ": empty list")
645 prel_list_str :: String
646 prel_list_str = "Prelude."