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 -- head and tail extract the first element and remaining elements,
58 -- respectively, of a list, which must be non-empty. last and init
59 -- are the dual functions working from the end of a finite list,
60 -- rather than the beginning.
66 badHead = errorEmptyList "head"
68 -- This rule is useful in cases like
69 -- head [y | (x,y) <- ps, x==t]
71 "head/build" forall (g::forall b.(Bool->b->b)->b->b) .
72 head (build g) = g (\x _ -> x) badHead
73 "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
74 head (augment g xs) = g (\x _ -> x) (head xs)
79 tail [] = errorEmptyList "tail"
82 #ifdef USE_REPORT_PRELUDE
85 last [] = errorEmptyList "last"
87 -- eliminate repeated cases
88 last [] = errorEmptyList "last"
89 last (x:xs) = last' x xs
91 last' _ (y:ys) = last' y ys
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
111 -- length returns the length of a finite list as an Int; it is an instance
112 -- of the more general genericLength, the result type of which may be
113 -- 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 those
122 -- elements that satisfy the predicate; i.e.,
123 -- filter p xs = [ x | x <- xs, p x]
124 filter :: (a -> Bool) -> [a] -> [a]
127 | pred x = x : filter pred xs
128 | otherwise = filter pred xs
130 {-# NOINLINE [0] filterFB #-}
131 filterFB c p x r | p x = x `c` r
135 "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
136 "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
137 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
140 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
141 -- filterFB (filterFB c p) q a b
142 -- = if q a then filterFB c p a b else b
143 -- = if q a then (if p a then c a b else b) else b
144 -- = if q a && p a then c a b else b
145 -- = filterFB c (\x -> q x && p x) a b
146 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
147 -- gave rise to a live bug report. SLPJ.
150 -- foldl, applied to a binary operator, a starting value (typically the
151 -- left-identity of the operator), and a list, reduces the list using
152 -- the binary operator, from left to right:
153 -- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
154 -- foldl1 is a variant that has no starting value argument, and thus must
155 -- be applied to non-empty lists. scanl is similar to foldl, but returns
156 -- a list of successive reduced values from the left:
157 -- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
158 -- Note that last (scanl f z xs) == foldl f z xs.
159 -- scanl1 is similar, again without the starting element:
160 -- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
162 -- We write foldl as a non-recursive thing, so that it
163 -- can be inlined, and then (often) strictness-analysed,
164 -- and hence the classic space leak on foldl (+) 0 xs
166 foldl :: (a -> b -> a) -> a -> [b] -> a
167 foldl f z xs = lgo z xs
170 lgo z (x:xs) = lgo (f z x) xs
172 foldl1 :: (a -> a -> a) -> [a] -> a
173 foldl1 f (x:xs) = foldl f x xs
174 foldl1 _ [] = errorEmptyList "foldl1"
176 scanl :: (a -> b -> a) -> a -> [b] -> [a]
177 scanl f q ls = q : (case ls of
179 x:xs -> scanl f (f q x) xs)
181 scanl1 :: (a -> a -> a) -> [a] -> [a]
182 scanl1 f (x:xs) = scanl f x xs
185 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
188 foldr1 :: (a -> a -> a) -> [a] -> a
190 foldr1 f (x:xs) = f x (foldr1 f xs)
191 foldr1 _ [] = errorEmptyList "foldr1"
193 scanr :: (a -> b -> b) -> b -> [a] -> [b]
195 scanr f q0 (x:xs) = f x q : qs
196 where qs@(q:_) = scanr f q0 xs
198 scanr1 :: (a -> a -> a) -> [a] -> [a]
201 scanr1 f (x:xs) = f x q : qs
202 where qs@(q:_) = scanr1 f xs
204 -- iterate f x returns an infinite list of repeated applications of f to x:
205 -- iterate f x == [x, f x, f (f x), ...]
206 iterate :: (a -> a) -> a -> [a]
207 iterate f x = x : iterate f (f x)
209 iterateFB c f x = x `c` iterateFB c f (f x)
213 "iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
214 "iterateFB" [1] iterateFB (:) = iterate
218 -- repeat x is an infinite list, with x the value of every element.
220 {-# INLINE [0] repeat #-}
221 -- The pragma just gives the rules more chance to fire
222 repeat x = xs where xs = x : xs
224 {-# INLINE [0] repeatFB #-} -- ditto
225 repeatFB c x = xs where xs = x `c` xs
229 "repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
230 "repeatFB" [1] repeatFB (:) = repeat
233 -- replicate n x is a list of length n with x the value of every element
234 replicate :: Int -> a -> [a]
235 replicate n x = take n (repeat x)
237 -- cycle ties a finite list into a circular one, or equivalently,
238 -- the infinite repetition of the original list. It is the identity
239 -- on infinite lists.
242 cycle [] = error "Prelude.cycle: empty list"
243 cycle xs = xs' where xs' = xs ++ xs'
245 -- takeWhile, applied to a predicate p and a list xs, returns the longest
246 -- prefix (possibly empty) of xs of elements that satisfy p. dropWhile p xs
247 -- returns the remaining suffix. Span p xs is equivalent to
248 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
250 takeWhile :: (a -> Bool) -> [a] -> [a]
253 | p x = x : takeWhile p xs
256 dropWhile :: (a -> Bool) -> [a] -> [a]
258 dropWhile p xs@(x:xs')
259 | p x = dropWhile p xs'
262 -- take n, applied to a list xs, returns the prefix of xs of length n,
263 -- or xs itself if n > length xs. drop n xs returns the suffix of xs
264 -- after the first n elements, or [] if n > length xs. splitAt n xs
265 -- is equivalent to (take n xs, drop n xs).
266 #ifdef USE_REPORT_PRELUDE
267 take :: Int -> [a] -> [a]
268 take n _ | n <= 0 = []
270 take n (x:xs) = x : take (n-1) xs
272 drop :: Int -> [a] -> [a]
273 drop n xs | n <= 0 = xs
275 drop n (_:xs) = drop (n-1) xs
277 splitAt :: Int -> [a] -> ([a],[a])
278 splitAt n xs = (take n xs, drop n xs)
280 #else /* hack away */
281 take :: Int -> [b] -> [b]
282 take (I# n#) xs = takeUInt n# xs
284 -- The general code for take, below, checks n <= maxInt
285 -- No need to check for maxInt overflow when specialised
286 -- at type Int or Int# since the Int must be <= maxInt
288 takeUInt :: Int# -> [b] -> [b]
290 | n >=# 0# = take_unsafe_UInt n xs
293 take_unsafe_UInt :: Int# -> [b] -> [b]
294 take_unsafe_UInt 0# _ = []
295 take_unsafe_UInt m ls =
298 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
300 takeUInt_append :: Int# -> [b] -> [b] -> [b]
301 takeUInt_append n xs rs
302 | n >=# 0# = take_unsafe_UInt_append n xs rs
305 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
306 take_unsafe_UInt_append 0# _ rs = rs
307 take_unsafe_UInt_append m ls rs =
310 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
312 drop :: Int -> [b] -> [b]
315 | otherwise = drop# n# ls
317 drop# :: Int# -> [a] -> [a]
320 drop# m# (_:xs) = drop# (m# -# 1#) xs
322 splitAt :: Int -> [b] -> ([b], [b])
324 | n# <# 0# = ([], ls)
325 | otherwise = splitAt# n# ls
327 splitAt# :: Int# -> [a] -> ([a], [a])
328 splitAt# 0# xs = ([], xs)
329 splitAt# _ xs@[] = (xs, xs)
330 splitAt# m# (x:xs) = (x:xs', xs'')
332 (xs', xs'') = splitAt# (m# -# 1#) xs
334 #endif /* USE_REPORT_PRELUDE */
336 span, break :: (a -> Bool) -> [a] -> ([a],[a])
337 span _ xs@[] = (xs, xs)
339 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
340 | otherwise = ([],xs)
342 #ifdef USE_REPORT_PRELUDE
343 break p = span (not . p)
345 -- HBC version (stolen)
346 break _ xs@[] = (xs, xs)
349 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
352 -- reverse xs returns the elements of xs in reverse order. xs must be finite.
353 reverse :: [a] -> [a]
354 #ifdef USE_REPORT_PRELUDE
355 reverse = foldl (flip (:)) []
360 rev (x:xs) a = rev xs (x:a)
363 -- and returns the conjunction of a Boolean list. For the result to be
364 -- True, the list must be finite; False, however, results from a False
365 -- value at a finite index of a finite or infinite list. or is the
366 -- disjunctive dual of and.
367 and, or :: [Bool] -> Bool
368 #ifdef USE_REPORT_PRELUDE
369 and = foldr (&&) True
370 or = foldr (||) False
373 and (x:xs) = x && and xs
375 or (x:xs) = x || or xs
378 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
379 and (build g) = g (&&) True
380 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
381 or (build g) = g (||) False
385 -- Applied to a predicate and a list, any determines if any element
386 -- of the list satisfies the predicate. Similarly, for all.
387 any, all :: (a -> Bool) -> [a] -> Bool
388 #ifdef USE_REPORT_PRELUDE
393 any p (x:xs) = p x || any p xs
396 all p (x:xs) = p x && all p xs
398 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
399 any p (build g) = g ((||) . p) False
400 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
401 all p (build g) = g ((&&) . p) True
405 -- elem is the list membership predicate, usually written in infix form,
406 -- e.g., x `elem` xs. notElem is the negation.
407 elem, notElem :: (Eq a) => a -> [a] -> Bool
408 #ifdef USE_REPORT_PRELUDE
410 notElem x = all (/= x)
413 elem x (y:ys) = x==y || elem x ys
416 notElem x (y:ys)= x /= y && notElem x ys
419 -- lookup key assocs looks up a key in an association list.
420 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
421 lookup _key [] = Nothing
422 lookup key ((x,y):xys)
424 | otherwise = lookup key xys
427 -- maximum and minimum return the maximum or minimum value from a list,
428 -- which must be non-empty, finite, and of an ordered type.
429 {-# SPECIALISE maximum :: [Int] -> Int #-}
430 {-# SPECIALISE minimum :: [Int] -> Int #-}
431 maximum, minimum :: (Ord a) => [a] -> a
432 maximum [] = errorEmptyList "maximum"
433 maximum xs = foldl1 max xs
435 minimum [] = errorEmptyList "minimum"
436 minimum xs = foldl1 min xs
438 concatMap :: (a -> [b]) -> [a] -> [b]
439 concatMap f = foldr ((++) . f) []
441 concat :: [[a]] -> [a]
442 concat = foldr (++) []
445 "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
446 -- We don't bother to turn non-fusible applications of concat back into concat
453 -- List index (subscript) operator, 0-origin
454 (!!) :: [a] -> Int -> a
455 #ifdef USE_REPORT_PRELUDE
456 xs !! n | n < 0 = error "Prelude.!!: negative index"
457 [] !! _ = error "Prelude.!!: index too large"
459 (_:xs) !! n = xs !! (n-1)
461 -- HBC version (stolen), then unboxified
462 -- The semantics is not quite the same for error conditions
463 -- in the more efficient version.
465 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
466 | otherwise = sub xs n
468 sub :: [a] -> Int# -> a
469 sub [] _ = error "Prelude.(!!): index too large\n"
470 sub (y:ys) n = if n ==# 0#
472 else sub ys (n -# 1#)
477 %*********************************************************
479 \subsection{The zip family}
481 %*********************************************************
484 foldr2 _k z [] _ys = z
485 foldr2 _k z _xs [] = z
486 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
488 foldr2_left _k z _x _r [] = z
489 foldr2_left k _z x r (y:ys) = k x y (r ys)
491 foldr2_right _k z _y _r [] = z
492 foldr2_right k _z y r (x:xs) = k x y (r xs)
494 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
495 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
497 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
498 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
500 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
501 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
505 The foldr2/right rule isn't exactly right, because it changes
506 the strictness of foldr2 (and thereby zip)
508 E.g. main = print (null (zip nonobviousNil (build undefined)))
509 where nonobviousNil = f 3
510 f n = if n == 0 then [] else f (n-1)
512 I'm going to leave it though.
515 zip takes two lists and returns a list of corresponding pairs. If one
516 input list is short, excess elements of the longer list are discarded.
517 zip3 takes three lists and returns a list of triples. Zips for larger
518 tuples are in the List module.
521 ----------------------------------------------
522 zip :: [a] -> [b] -> [(a,b)]
523 zip (a:as) (b:bs) = (a,b) : zip as bs
526 {-# INLINE [0] zipFB #-}
527 zipFB c x y r = (x,y) `c` r
530 "zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
531 "zipList" [1] foldr2 (zipFB (:)) [] = zip
536 ----------------------------------------------
537 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
539 -- zip3 = zipWith3 (,,)
540 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
545 -- The zipWith family generalises the zip family by zipping with the
546 -- function given as the first argument, instead of a tupling function.
547 -- For example, zipWith (+) is applied to two lists to produce the list
548 -- of corresponding sums.
552 ----------------------------------------------
553 zipWith :: (a->b->c) -> [a]->[b]->[c]
554 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
557 {-# INLINE [0] zipWithFB #-}
558 zipWithFB c f x y r = (x `f` y) `c` r
561 "zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
562 "zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
567 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
568 zipWith3 z (a:as) (b:bs) (c:cs)
569 = z a b c : zipWith3 z as bs cs
570 zipWith3 _ _ _ _ = []
572 -- unzip transforms a list of pairs into a pair of lists.
573 unzip :: [(a,b)] -> ([a],[b])
575 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
577 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
578 {-# INLINE unzip3 #-}
579 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
584 %*********************************************************
586 \subsection{Error code}
588 %*********************************************************
590 Common up near identical calls to `error' to reduce the number
591 constant strings created when compiled:
594 errorEmptyList :: String -> a
596 error (prel_list_str ++ fun ++ ": empty list")
598 prel_list_str :: String
599 prel_list_str = "Prelude."