2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[PrelList]{Module @PrelList@}
7 The List data type and its operations
10 {-# OPTIONS -fno-implicit-prelude #-}
15 map, (++), filter, concat,
16 head, last, tail, init, null, length, (!!),
17 foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
18 iterate, repeat, replicate, cycle,
19 take, drop, splitAt, takeWhile, dropWhile, span, break,
21 any, all, elem, notElem, lookup,
22 maximum, minimum, concatMap,
23 zip, zip3, zipWith, zipWith3, unzip, unzip3,
24 #ifdef USE_REPORT_PRELUDE
28 -- non-standard, but hidden when creating the Prelude
36 import {-# SOURCE #-} PrelErr ( error )
42 infix 4 `elem`, `notElem`
45 %*********************************************************
47 \subsection{List-manipulation functions}
49 %*********************************************************
52 -- head and tail extract the first element and remaining elements,
53 -- respectively, of a list, which must be non-empty. last and init
54 -- are the dual functions working from the end of a finite list,
55 -- rather than the beginning.
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)
74 tail [] = errorEmptyList "tail"
77 #ifdef USE_REPORT_PRELUDE
80 last [] = errorEmptyList "last"
82 -- eliminate repeated cases
83 last [] = errorEmptyList "last"
84 last (x:xs) = last' x xs
86 last' _ (y:ys) = last' y ys
90 #ifdef USE_REPORT_PRELUDE
92 init (x:xs) = x : init xs
93 init [] = errorEmptyList "init"
95 -- eliminate repeated cases
96 init [] = errorEmptyList "init"
97 init (x:xs) = init' x xs
99 init' y (z:zs) = y : init' z zs
106 -- length returns the length of a finite list as an Int; it is an instance
107 -- of the more general genericLength, the result type of which may be
108 -- any kind of number.
112 len :: [a] -> Int# -> Int
114 len (_:xs) a# = len xs (a# +# 1#)
116 -- filter, applied to a predicate and a list, returns the list of those
117 -- elements that satisfy the predicate; i.e.,
118 -- filter p xs = [ x | x <- xs, p x]
119 filter :: (a -> Bool) -> [a] -> [a]
122 filterFB c p x r | p x = x `c` r
126 "filter" forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
127 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
128 "filterList" forall p. foldr (filterFB (:) p) [] = filterList p
131 filterList :: (a -> Bool) -> [a] -> [a]
132 filterList _pred [] = []
133 filterList pred (x:xs)
134 | pred x = x : filterList pred xs
135 | otherwise = filterList pred xs
137 -- foldl, applied to a binary operator, a starting value (typically the
138 -- left-identity of the operator), and a list, reduces the list using
139 -- the binary operator, from left to right:
140 -- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
141 -- foldl1 is a variant that has no starting value argument, and thus must
142 -- be applied to non-empty lists. scanl is similar to foldl, but returns
143 -- a list of successive reduced values from the left:
144 -- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
145 -- Note that last (scanl f z xs) == foldl f z xs.
146 -- scanl1 is similar, again without the starting element:
147 -- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
149 foldl :: (a -> b -> a) -> a -> [b] -> a
151 foldl f z (x:xs) = foldl f (f z x) xs
153 foldl1 :: (a -> a -> a) -> [a] -> a
154 foldl1 f (x:xs) = foldl f x xs
155 foldl1 _ [] = errorEmptyList "foldl1"
157 scanl :: (a -> b -> a) -> a -> [b] -> [a]
158 scanl f q ls = q : (case ls of
160 x:xs -> scanl f (f q x) xs)
162 scanl1 :: (a -> a -> a) -> [a] -> [a]
163 scanl1 f (x:xs) = scanl f x xs
164 scanl1 _ [] = errorEmptyList "scanl1"
166 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
169 foldr1 :: (a -> a -> a) -> [a] -> a
171 foldr1 f (x:xs) = f x (foldr1 f xs)
172 foldr1 _ [] = errorEmptyList "foldr1"
174 scanr :: (a -> b -> b) -> b -> [a] -> [b]
176 scanr f q0 (x:xs) = f x q : qs
177 where qs@(q:_) = scanr f q0 xs
179 scanr1 :: (a -> a -> a) -> [a] -> [a]
181 scanr1 f (x:xs) = f x q : qs
182 where qs@(q:_) = scanr1 f xs
183 scanr1 _ [] = errorEmptyList "scanr1"
185 -- iterate f x returns an infinite list of repeated applications of f to x:
186 -- iterate f x == [x, f x, f (f x), ...]
187 iterate :: (a -> a) -> a -> [a]
188 iterate = iterateList
190 iterateFB c f x = x `c` iterateFB c f (f x)
192 iterateList f x = x : iterateList f (f x)
195 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
196 "iterateFB" iterateFB (:) = iterateList
200 -- repeat x is an infinite list, with x the value of every element.
204 repeatFB c x = xs where xs = x `c` xs
205 repeatList x = xs where xs = x : xs
208 "repeat" forall x. repeat x = build (\c _n -> repeatFB c x)
209 "repeatFB" repeatFB (:) = repeatList
212 -- replicate n x is a list of length n with x the value of every element
213 replicate :: Int -> a -> [a]
214 replicate n x = take n (repeat x)
216 -- cycle ties a finite list into a circular one, or equivalently,
217 -- the infinite repetition of the original list. It is the identity
218 -- on infinite lists.
221 cycle [] = error "Prelude.cycle: empty list"
222 cycle xs = xs' where xs' = xs ++ xs'
224 -- takeWhile, applied to a predicate p and a list xs, returns the longest
225 -- prefix (possibly empty) of xs of elements that satisfy p. dropWhile p xs
226 -- returns the remaining suffix. Span p xs is equivalent to
227 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
229 takeWhile :: (a -> Bool) -> [a] -> [a]
232 | p x = x : takeWhile p xs
235 dropWhile :: (a -> Bool) -> [a] -> [a]
237 dropWhile p xs@(x:xs')
238 | p x = dropWhile p xs'
241 -- take n, applied to a list xs, returns the prefix of xs of length n,
242 -- or xs itself if n > length xs. drop n xs returns the suffix of xs
243 -- after the first n elements, or [] if n > length xs. splitAt n xs
244 -- is equivalent to (take n xs, drop n xs).
245 #ifdef USE_REPORT_PRELUDE
246 take :: Int -> [a] -> [a]
249 take n (x:xs) | n > 0 = x : take (minusInt n 1) xs
250 take _ _ = errorNegativeIdx "take"
252 drop :: Int -> [a] -> [a]
255 drop n (_:xs) | n > 0 = drop (minusInt n 1) xs
256 drop _ _ = errorNegativeIdx "drop"
259 splitAt :: Int -> [a] -> ([a],[a])
260 splitAt 0 xs = ([],xs)
261 splitAt _ [] = ([],[])
262 splitAt n (x:xs) | n > 0 = (x:xs',xs'') where (xs',xs'') = splitAt (minusInt n 1) xs
263 splitAt _ _ = errorNegativeIdx "splitAt"
265 #else /* hack away */
266 take :: Int -> [b] -> [b]
267 take (I# n#) xs = takeUInt n# xs
269 -- The general code for take, below, checks n <= maxInt
270 -- No need to check for maxInt overflow when specialised
271 -- at type Int or Int# since the Int must be <= maxInt
273 takeUInt :: Int# -> [b] -> [b]
275 | n >=# 0# = take_unsafe_UInt n xs
276 | otherwise = errorNegativeIdx "take"
278 take_unsafe_UInt :: Int# -> [b] -> [b]
279 take_unsafe_UInt 0# _ = []
280 take_unsafe_UInt m ls =
283 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
285 takeUInt_append :: Int# -> [b] -> [b] -> [b]
286 takeUInt_append n xs rs
287 | n >=# 0# = take_unsafe_UInt_append n xs rs
288 | otherwise = errorNegativeIdx "take"
290 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
291 take_unsafe_UInt_append 0# _ rs = rs
292 take_unsafe_UInt_append m ls rs =
295 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
297 drop :: Int -> [b] -> [b]
299 | n# <# 0# = errorNegativeIdx "drop"
300 | otherwise = drop# n# ls
302 drop# :: Int# -> [a] -> [a]
305 drop# m# (_:xs) = drop# (m# -# 1#) xs
307 splitAt :: Int -> [b] -> ([b], [b])
309 | n# <# 0# = errorNegativeIdx "splitAt"
310 | otherwise = splitAt# n# ls
312 splitAt# :: Int# -> [a] -> ([a], [a])
313 splitAt# 0# xs = ([], xs)
314 splitAt# _ xs@[] = (xs, xs)
315 splitAt# m# (x:xs) = (x:xs', xs'')
317 (xs', xs'') = splitAt# (m# -# 1#) xs
319 #endif /* USE_REPORT_PRELUDE */
321 span, break :: (a -> Bool) -> [a] -> ([a],[a])
322 span _ xs@[] = (xs, xs)
324 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
325 | otherwise = ([],xs)
327 #ifdef USE_REPORT_PRELUDE
328 break p = span (not . p)
330 -- HBC version (stolen)
331 break _ xs@[] = (xs, xs)
334 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
337 -- reverse xs returns the elements of xs in reverse order. xs must be finite.
338 reverse :: [a] -> [a]
339 #ifdef USE_REPORT_PRELUDE
340 reverse = foldl (flip (:)) []
345 rev (x:xs) a = rev xs (x:a)
348 -- and returns the conjunction of a Boolean list. For the result to be
349 -- True, the list must be finite; False, however, results from a False
350 -- value at a finite index of a finite or infinite list. or is the
351 -- disjunctive dual of and.
352 and, or :: [Bool] -> Bool
353 #ifdef USE_REPORT_PRELUDE
354 and = foldr (&&) True
355 or = foldr (||) False
358 and (x:xs) = x && and xs
360 or (x:xs) = x || or xs
363 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
364 and (build g) = g (&&) True
365 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
366 or (build g) = g (||) False
370 -- Applied to a predicate and a list, any determines if any element
371 -- of the list satisfies the predicate. Similarly, for all.
372 any, all :: (a -> Bool) -> [a] -> Bool
373 #ifdef USE_REPORT_PRELUDE
378 any p (x:xs) = p x || any p xs
381 all p (x:xs) = p x && all p xs
383 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
384 any p (build g) = g ((||) . p) False
385 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
386 all p (build g) = g ((&&) . p) True
390 -- elem is the list membership predicate, usually written in infix form,
391 -- e.g., x `elem` xs. notElem is the negation.
392 elem, notElem :: (Eq a) => a -> [a] -> Bool
393 #ifdef USE_REPORT_PRELUDE
395 notElem x = all (/= x)
398 elem x (y:ys) = x==y || elem x ys
401 notElem x (y:ys)= x /= y && notElem x ys
404 -- lookup key assocs looks up a key in an association list.
405 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
406 lookup _key [] = Nothing
407 lookup key ((x,y):xys)
409 | otherwise = lookup key xys
412 -- maximum and minimum return the maximum or minimum value from a list,
413 -- which must be non-empty, finite, and of an ordered type.
414 {-# SPECIALISE maximum :: [Int] -> Int #-}
415 {-# SPECIALISE minimum :: [Int] -> Int #-}
416 maximum, minimum :: (Ord a) => [a] -> a
417 maximum [] = errorEmptyList "maximum"
418 maximum xs = foldl1 max xs
420 minimum [] = errorEmptyList "minimum"
421 minimum xs = foldl1 min xs
423 concatMap :: (a -> [b]) -> [a] -> [b]
424 concatMap f = foldr ((++) . f) []
426 concat :: [[a]] -> [a]
427 {-# INLINE concat #-}
428 concat = foldr (++) []
433 -- List index (subscript) operator, 0-origin
434 (!!) :: [a] -> Int -> a
435 #ifdef USE_REPORT_PRELUDE
437 (_:xs) !! n | n > 0 = xs !! (minusInt n 1)
438 (_:_) !! _ = error "Prelude.(!!): negative index"
439 [] !! _ = error "Prelude.(!!): index too large"
441 -- HBC version (stolen), then unboxified
442 -- The semantics is not quite the same for error conditions
443 -- in the more efficient version.
445 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
446 | otherwise = sub xs n
448 sub :: [a] -> Int# -> a
449 sub [] _ = error "Prelude.(!!): index too large\n"
450 sub (y:ys) n = if n ==# 0#
452 else sub ys (n -# 1#)
457 %*********************************************************
459 \subsection{The zip family}
461 %*********************************************************
464 foldr2 _k z [] _ys = z
465 foldr2 _k z _xs [] = z
466 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
468 foldr2_left _k z _x _r [] = z
469 foldr2_left k _z x r (y:ys) = k x y (r ys)
471 foldr2_right _k z _y _r [] = z
472 foldr2_right k _z y r (x:xs) = k x y (r xs)
474 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
475 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
477 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
478 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
480 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
481 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
485 The foldr2/right rule isn't exactly right, because it changes
486 the strictness of foldr2 (and thereby zip)
488 E.g. main = print (null (zip nonobviousNil (build undefined)))
489 where nonobviousNil = f 3
490 f n = if n == 0 then [] else f (n-1)
492 I'm going to leave it though.
495 zip takes two lists and returns a list of corresponding pairs. If one
496 input list is short, excess elements of the longer list are discarded.
497 zip3 takes three lists and returns a list of triples. Zips for larger
498 tuples are in the List library
501 ----------------------------------------------
502 zip :: [a] -> [b] -> [(a,b)]
505 zipFB c x y r = (x,y) `c` r
508 zipList :: [a] -> [b] -> [(a,b)]
509 zipList (a:as) (b:bs) = (a,b) : zipList as bs
513 "zip" forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
514 "zipList" foldr2 (zipFB (:)) [] = zipList
519 ----------------------------------------------
520 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
522 -- zip3 = zipWith3 (,,)
523 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
528 -- The zipWith family generalises the zip family by zipping with the
529 -- function given as the first argument, instead of a tupling function.
530 -- For example, zipWith (+) is applied to two lists to produce the list
531 -- of corresponding sums.
535 ----------------------------------------------
536 zipWith :: (a->b->c) -> [a]->[b]->[c]
537 zipWith = zipWithList
540 zipWithFB c f x y r = (x `f` y) `c` r
542 zipWithList :: (a->b->c) -> [a] -> [b] -> [c]
543 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
544 zipWithList _ _ _ = []
547 "zipWith" forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
548 "zipWithList" forall f. foldr2 (zipWithFB (:) f) [] = zipWithList f
553 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
554 zipWith3 z (a:as) (b:bs) (c:cs)
555 = z a b c : zipWith3 z as bs cs
556 zipWith3 _ _ _ _ = []
558 -- unzip transforms a list of pairs into a pair of lists.
559 unzip :: [(a,b)] -> ([a],[b])
561 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
563 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
564 {-# INLINE unzip3 #-}
565 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
570 %*********************************************************
572 \subsection{Error code}
574 %*********************************************************
576 Common up near identical calls to `error' to reduce the number
577 constant strings created when compiled:
580 errorEmptyList :: String -> a
582 error (prel_list_str ++ fun ++ ": empty list")
584 errorNegativeIdx :: String -> a
585 errorNegativeIdx fun =
586 error (prel_list_str ++ fun ++ ": negative index")
588 prel_list_str :: String
589 prel_list_str = "Prelude."