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, foldl1, 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,
27 maximum, minimum, concatMap,
28 zip, zip3, zipWith, zipWith3, unzip, unzip3,
29 #ifdef USE_REPORT_PRELUDE
33 -- non-standard, but hidden when creating the Prelude
41 import {-# SOURCE #-} GHC.Err ( error )
47 infix 4 `elem`, `notElem`
50 %*********************************************************
52 \subsection{List-manipulation functions}
54 %*********************************************************
57 -- | Extract the first element of a list, which must be non-empty.
62 badHead = errorEmptyList "head"
64 -- This rule is useful in cases like
65 -- head [y | (x,y) <- ps, x==t]
67 "head/build" forall (g::forall b.(Bool->b->b)->b->b) .
68 head (build g) = g (\x _ -> x) badHead
69 "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
70 head (augment g xs) = g (\x _ -> x) (head xs)
73 -- | Extract the elements after the head of a list, which must be non-empty.
76 tail [] = errorEmptyList "tail"
78 -- | Extract the last element of a list, which must be finite and non-empty.
80 #ifdef USE_REPORT_PRELUDE
83 last [] = errorEmptyList "last"
85 -- eliminate repeated cases
86 last [] = errorEmptyList "last"
87 last (x:xs) = last' x xs
89 last' _ (y:ys) = last' y ys
92 -- | Return all the elements of a list except the last one.
93 -- The list must be finite and non-empty.
95 #ifdef USE_REPORT_PRELUDE
97 init (x:xs) = x : init xs
98 init [] = errorEmptyList "init"
100 -- eliminate repeated cases
101 init [] = errorEmptyList "init"
102 init (x:xs) = init' x xs
103 where init' _ [] = []
104 init' y (z:zs) = y : init' z zs
107 -- | Test whether a list is empty.
112 -- | 'length' returns the length of a finite list as an 'Int'.
113 -- It is an instance of the more general 'Data.List.genericLength',
114 -- the result type of which may be any kind of number.
118 len :: [a] -> Int# -> Int
120 len (_:xs) a# = len xs (a# +# 1#)
122 -- | 'filter', applied to a predicate and a list, returns the list of
123 -- those elements that satisfy the predicate; i.e.,
125 -- > filter p xs = [ x | x <- xs, p x]
127 filter :: (a -> Bool) -> [a] -> [a]
130 | pred x = x : filter pred xs
131 | otherwise = filter pred xs
133 {-# NOINLINE [0] filterFB #-}
134 filterFB c p x r | p x = x `c` r
138 "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
139 "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
140 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
143 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
144 -- filterFB (filterFB c p) q a b
145 -- = if q a then filterFB c p a b else b
146 -- = if q a then (if p a then c a b else b) else b
147 -- = if q a && p a then c a b else b
148 -- = filterFB c (\x -> q x && p x) a b
149 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
150 -- gave rise to a live bug report. SLPJ.
153 -- | 'foldl', applied to a binary operator, a starting value (typically
154 -- the left-identity of the operator), and a list, reduces the list
155 -- using the binary operator, from left to right:
157 -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
159 -- The list must be finite.
161 -- We write foldl as a non-recursive thing, so that it
162 -- can be inlined, and then (often) strictness-analysed,
163 -- and hence the classic space leak on foldl (+) 0 xs
165 foldl :: (a -> b -> a) -> a -> [b] -> a
166 foldl f z xs = lgo z xs
169 lgo z (x:xs) = lgo (f z x) xs
171 -- | 'foldl1' is a variant of 'foldl' that has no starting value argument,
172 -- and thus must be applied to non-empty lists.
174 foldl1 :: (a -> a -> a) -> [a] -> a
175 foldl1 f (x:xs) = foldl f x xs
176 foldl1 _ [] = errorEmptyList "foldl1"
178 -- | 'scanl' is similar to 'foldl', but returns a list of successive
179 -- reduced values from the left:
181 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
185 -- > last (scanl f z xs) == foldl f z xs.
187 scanl :: (a -> b -> a) -> a -> [b] -> [a]
188 scanl f q ls = q : (case ls of
190 x:xs -> scanl f (f q x) xs)
192 -- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
194 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
196 scanl1 :: (a -> a -> a) -> [a] -> [a]
197 scanl1 f (x:xs) = scanl f x xs
200 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
203 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
204 -- and thus must be applied to non-empty lists.
206 foldr1 :: (a -> a -> a) -> [a] -> a
208 foldr1 f (x:xs) = f x (foldr1 f xs)
209 foldr1 _ [] = errorEmptyList "foldr1"
211 -- | 'scanr' is the right-to-left dual of 'scanl'.
214 -- > head (scanr f z xs) == foldr f z xs.
216 scanr :: (a -> b -> b) -> b -> [a] -> [b]
218 scanr f q0 (x:xs) = f x q : qs
219 where qs@(q:_) = scanr f q0 xs
221 -- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
223 scanr1 :: (a -> a -> a) -> [a] -> [a]
226 scanr1 f (x:xs) = f x q : qs
227 where qs@(q:_) = scanr1 f xs
229 -- | 'iterate' @f x@ returns an infinite list of repeated applications
232 -- > iterate f x == [x, f x, f (f x), ...]
234 iterate :: (a -> a) -> a -> [a]
235 iterate f x = x : iterate f (f x)
237 iterateFB c f x = x `c` iterateFB c f (f x)
241 "iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
242 "iterateFB" [1] iterateFB (:) = iterate
246 -- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
248 {-# INLINE [0] repeat #-}
249 -- The pragma just gives the rules more chance to fire
250 repeat x = xs where xs = x : xs
252 {-# INLINE [0] repeatFB #-} -- ditto
253 repeatFB c x = xs where xs = x `c` xs
257 "repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
258 "repeatFB" [1] repeatFB (:) = repeat
261 -- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
263 -- It is an instance of the more general 'Data.List.genericReplicate',
264 -- in which @n@ may be of any integral type.
265 replicate :: Int -> a -> [a]
266 replicate n x = take n (repeat x)
268 -- | 'cycle' ties a finite list into a circular one, or equivalently,
269 -- the infinite repetition of the original list. It is the identity
270 -- on infinite lists.
273 cycle [] = error "Prelude.cycle: empty list"
274 cycle xs = xs' where xs' = xs ++ xs'
276 -- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
277 -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@.
279 takeWhile :: (a -> Bool) -> [a] -> [a]
282 | p x = x : takeWhile p xs
285 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
287 dropWhile :: (a -> Bool) -> [a] -> [a]
289 dropWhile p xs@(x:xs')
290 | p x = dropWhile p xs'
293 -- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
294 -- of length @n@, or @xs@ itself if @n > 'length' xs@.
295 -- It is an instance of the more general 'Data.List.genericTake',
296 -- in which @n@ may be of any integral type.
297 take :: Int -> [a] -> [a]
299 -- | 'drop' @n xs@ returns the suffix of @xs@
300 -- after the first @n@ elements, or @[]@ if @n > 'length' xs@.
301 -- It is an instance of the more general 'Data.List.genericDrop',
302 -- in which @n@ may be of any integral type.
303 drop :: Int -> [a] -> [a]
305 -- | 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
306 -- It is an instance of the more general 'Data.List.genericSplitAt',
307 -- in which @n@ may be of any integral type.
308 splitAt :: Int -> [a] -> ([a],[a])
310 #ifdef USE_REPORT_PRELUDE
311 take n _ | n <= 0 = []
313 take n (x:xs) = x : take (n-1) xs
315 drop n xs | n <= 0 = xs
317 drop n (_:xs) = drop (n-1) xs
319 splitAt n xs = (take n xs, drop n xs)
321 #else /* hack away */
322 take (I# n#) xs = takeUInt n# xs
324 -- The general code for take, below, checks n <= maxInt
325 -- No need to check for maxInt overflow when specialised
326 -- at type Int or Int# since the Int must be <= maxInt
328 takeUInt :: Int# -> [b] -> [b]
330 | n >=# 0# = take_unsafe_UInt n xs
333 take_unsafe_UInt :: Int# -> [b] -> [b]
334 take_unsafe_UInt 0# _ = []
335 take_unsafe_UInt m ls =
338 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
340 takeUInt_append :: Int# -> [b] -> [b] -> [b]
341 takeUInt_append n xs rs
342 | n >=# 0# = take_unsafe_UInt_append n xs rs
345 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
346 take_unsafe_UInt_append 0# _ rs = rs
347 take_unsafe_UInt_append m ls rs =
350 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
354 | otherwise = drop# n# ls
356 drop# :: Int# -> [a] -> [a]
359 drop# m# (_:xs) = drop# (m# -# 1#) xs
362 | n# <# 0# = ([], ls)
363 | otherwise = splitAt# n# ls
365 splitAt# :: Int# -> [a] -> ([a], [a])
366 splitAt# 0# xs = ([], xs)
367 splitAt# _ xs@[] = (xs, xs)
368 splitAt# m# (x:xs) = (x:xs', xs'')
370 (xs', xs'') = splitAt# (m# -# 1#) xs
372 #endif /* USE_REPORT_PRELUDE */
374 -- | 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
376 span :: (a -> Bool) -> [a] -> ([a],[a])
377 span _ xs@[] = (xs, xs)
379 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
380 | otherwise = ([],xs)
382 -- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
384 break :: (a -> Bool) -> [a] -> ([a],[a])
385 #ifdef USE_REPORT_PRELUDE
386 break p = span (not . p)
388 -- HBC version (stolen)
389 break _ xs@[] = (xs, xs)
392 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
395 -- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
396 -- @xs@ must be finite.
397 reverse :: [a] -> [a]
398 #ifdef USE_REPORT_PRELUDE
399 reverse = foldl (flip (:)) []
404 rev (x:xs) a = rev xs (x:a)
407 -- | 'and' returns the conjunction of a Boolean list. For the result to be
408 -- 'True', the list must be finite; 'False', however, results from a 'False'
409 -- value at a finite index of a finite or infinite list.
410 and :: [Bool] -> Bool
412 -- | 'or' returns the disjunction of a Boolean list. For the result to be
413 -- 'False', the list must be finite; 'True', however, results from a 'True'
414 -- value at a finite index of a finite or infinite list.
416 #ifdef USE_REPORT_PRELUDE
417 and = foldr (&&) True
418 or = foldr (||) False
421 and (x:xs) = x && and xs
423 or (x:xs) = x || or xs
426 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
427 and (build g) = g (&&) True
428 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
429 or (build g) = g (||) False
433 -- | Applied to a predicate and a list, 'any' determines if any element
434 -- of the list satisfies the predicate.
435 any :: (a -> Bool) -> [a] -> Bool
437 -- | Applied to a predicate and a list, 'all' determines if all elements
438 -- of the list satisfy the predicate.
439 all :: (a -> Bool) -> [a] -> Bool
440 #ifdef USE_REPORT_PRELUDE
445 any p (x:xs) = p x || any p xs
448 all p (x:xs) = p x && all p xs
450 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
451 any p (build g) = g ((||) . p) False
452 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
453 all p (build g) = g ((&&) . p) True
457 -- | 'elem' is the list membership predicate, usually written in infix form,
458 -- e.g., @x `elem` xs@.
459 elem :: (Eq a) => a -> [a] -> Bool
461 -- | 'notElem' is the negation of 'elem'.
462 notElem :: (Eq a) => a -> [a] -> Bool
463 #ifdef USE_REPORT_PRELUDE
465 notElem x = all (/= x)
468 elem x (y:ys) = x==y || elem x ys
471 notElem x (y:ys)= x /= y && notElem x ys
474 -- | 'lookup' @key assocs@ looks up a key in an association list.
475 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
476 lookup _key [] = Nothing
477 lookup key ((x,y):xys)
479 | otherwise = lookup key xys
481 {-# SPECIALISE maximum :: [Int] -> Int #-}
482 {-# SPECIALISE minimum :: [Int] -> Int #-}
484 -- | 'maximum' returns the maximum value from a list,
485 -- which must be non-empty, finite, and of an ordered type.
486 -- It is a special case of 'Data.List.maximumBy', which allows the
487 -- programmer to supply their own comparison function.
488 maximum :: (Ord a) => [a] -> a
489 maximum [] = errorEmptyList "maximum"
490 maximum xs = foldl1 max xs
492 -- | 'minimum' returns the minimum value from a list,
493 -- which must be non-empty, finite, and of an ordered type.
494 -- It is a special case of 'Data.List.minimumBy', which allows the
495 -- programmer to supply their own comparison function.
496 minimum :: (Ord a) => [a] -> a
497 minimum [] = errorEmptyList "minimum"
498 minimum xs = foldl1 min xs
500 -- | Map a function over a list and concatenate the results.
501 concatMap :: (a -> [b]) -> [a] -> [b]
502 concatMap f = foldr ((++) . f) []
504 -- | Concatenate a list of lists.
505 concat :: [[a]] -> [a]
506 concat = foldr (++) []
509 "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
510 -- We don't bother to turn non-fusible applications of concat back into concat
517 -- | List index (subscript) operator, starting from 0.
518 -- It is an instance of the more general 'Data.List.genericIndex',
519 -- which takes an index of any integral type.
520 (!!) :: [a] -> Int -> a
521 #ifdef USE_REPORT_PRELUDE
522 xs !! n | n < 0 = error "Prelude.!!: negative index"
523 [] !! _ = error "Prelude.!!: index too large"
525 (_:xs) !! n = xs !! (n-1)
527 -- HBC version (stolen), then unboxified
528 -- The semantics is not quite the same for error conditions
529 -- in the more efficient version.
531 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
532 | otherwise = sub xs n
534 sub :: [a] -> Int# -> a
535 sub [] _ = error "Prelude.(!!): index too large\n"
536 sub (y:ys) n = if n ==# 0#
538 else sub ys (n -# 1#)
543 %*********************************************************
545 \subsection{The zip family}
547 %*********************************************************
550 foldr2 _k z [] _ys = z
551 foldr2 _k z _xs [] = z
552 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
554 foldr2_left _k z _x _r [] = z
555 foldr2_left k _z x r (y:ys) = k x y (r ys)
557 foldr2_right _k z _y _r [] = z
558 foldr2_right k _z y r (x:xs) = k x y (r xs)
560 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
561 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
563 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
564 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
566 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
567 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
571 The foldr2/right rule isn't exactly right, because it changes
572 the strictness of foldr2 (and thereby zip)
574 E.g. main = print (null (zip nonobviousNil (build undefined)))
575 where nonobviousNil = f 3
576 f n = if n == 0 then [] else f (n-1)
578 I'm going to leave it though.
581 Zips for larger tuples are in the List module.
584 ----------------------------------------------
585 -- | 'zip' takes two lists and returns a list of corresponding pairs.
586 -- If one input list is short, excess elements of the longer list are
588 zip :: [a] -> [b] -> [(a,b)]
589 zip (a:as) (b:bs) = (a,b) : zip as bs
592 {-# INLINE [0] zipFB #-}
593 zipFB c x y r = (x,y) `c` r
596 "zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
597 "zipList" [1] foldr2 (zipFB (:)) [] = zip
602 ----------------------------------------------
603 -- | 'zip3' takes three lists and returns a list of triples, analogous to
605 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
607 -- zip3 = zipWith3 (,,)
608 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
613 -- The zipWith family generalises the zip family by zipping with the
614 -- function given as the first argument, instead of a tupling function.
617 ----------------------------------------------
618 -- | 'zipWith' generalises 'zip' by zipping with the function given
619 -- as the first argument, instead of a tupling function.
620 -- For example, @'zipWith' (+)@ is applied to two lists to produce the
621 -- list of corresponding sums.
622 zipWith :: (a->b->c) -> [a]->[b]->[c]
623 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
626 {-# INLINE [0] zipWithFB #-}
627 zipWithFB c f x y r = (x `f` y) `c` r
630 "zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
631 "zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
636 -- | The 'zipWith3' function takes a function which combines three
637 -- elements, as well as three lists and returns a list of their point-wise
638 -- combination, analogous to 'zipWith'.
639 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
640 zipWith3 z (a:as) (b:bs) (c:cs)
641 = z a b c : zipWith3 z as bs cs
642 zipWith3 _ _ _ _ = []
644 -- | 'unzip' transforms a list of pairs into a list of first components
645 -- and a list of second components.
646 unzip :: [(a,b)] -> ([a],[b])
648 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
650 -- | The 'unzip3' function takes a list of triples and returns three
651 -- lists, analogous to 'unzip'.
652 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
653 {-# INLINE unzip3 #-}
654 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
659 %*********************************************************
661 \subsection{Error code}
663 %*********************************************************
665 Common up near identical calls to `error' to reduce the number
666 constant strings created when compiled:
669 errorEmptyList :: String -> a
671 error (prel_list_str ++ fun ++ ": empty list")
673 prel_list_str :: String
674 prel_list_str = "Prelude."