1 % ------------------------------------------------------------------------------
2 % $Id: PrelList.lhs,v 1.20 2000/06/30 13:39:35 simonmar Exp $
4 % (c) The University of Glasgow, 1994-2000
7 \section[PrelList]{Module @PrelList@}
9 The List data type and its operations
12 {-# OPTIONS -fno-implicit-prelude #-}
17 map, (++), filter, concat,
18 head, last, tail, init, null, length, (!!),
19 foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
20 iterate, repeat, replicate, cycle,
21 take, drop, splitAt, takeWhile, dropWhile, span, break,
23 any, all, elem, notElem, lookup,
24 maximum, minimum, concatMap,
25 zip, zip3, zipWith, zipWith3, unzip, unzip3,
26 #ifdef USE_REPORT_PRELUDE
30 -- non-standard, but hidden when creating the Prelude
38 import {-# SOURCE #-} PrelErr ( error )
44 infix 4 `elem`, `notElem`
47 %*********************************************************
49 \subsection{List-manipulation functions}
51 %*********************************************************
54 -- head and tail extract the first element and remaining elements,
55 -- respectively, of a list, which must be non-empty. last and init
56 -- are the dual functions working from the end of a finite list,
57 -- rather than the beginning.
63 badHead = errorEmptyList "head"
65 -- This rule is useful in cases like
66 -- head [y | (x,y) <- ps, x==t]
68 "head/build" forall (g::forall b.(Bool->b->b)->b->b) .
69 head (build g) = g (\x _ -> x) badHead
70 "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
71 head (augment g xs) = g (\x _ -> x) (head xs)
76 tail [] = errorEmptyList "tail"
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
92 #ifdef USE_REPORT_PRELUDE
94 init (x:xs) = x : init xs
95 init [] = errorEmptyList "init"
97 -- eliminate repeated cases
98 init [] = errorEmptyList "init"
99 init (x:xs) = init' x xs
100 where init' _ [] = []
101 init' y (z:zs) = y : init' z zs
108 -- length returns the length of a finite list as an Int; it is an instance
109 -- of the more general genericLength, the result type of which may be
110 -- any kind of number.
114 len :: [a] -> Int# -> Int
116 len (_:xs) a# = len xs (a# +# 1#)
118 -- filter, applied to a predicate and a list, returns the list of those
119 -- elements that satisfy the predicate; i.e.,
120 -- filter p xs = [ x | x <- xs, p x]
121 filter :: (a -> Bool) -> [a] -> [a]
124 filterFB c p x r | p x = x `c` r
128 "filter" forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
129 "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
130 "filterList" forall p. foldr (filterFB (:) p) [] = filterList p
133 filterList :: (a -> Bool) -> [a] -> [a]
134 filterList _pred [] = []
135 filterList pred (x:xs)
136 | pred x = x : filterList pred xs
137 | otherwise = filterList pred xs
139 -- foldl, applied to a binary operator, a starting value (typically the
140 -- left-identity of the operator), and a list, reduces the list using
141 -- the binary operator, from left to right:
142 -- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
143 -- foldl1 is a variant that has no starting value argument, and thus must
144 -- be applied to non-empty lists. scanl is similar to foldl, but returns
145 -- a list of successive reduced values from the left:
146 -- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
147 -- Note that last (scanl f z xs) == foldl f z xs.
148 -- scanl1 is similar, again without the starting element:
149 -- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
151 foldl :: (a -> b -> a) -> a -> [b] -> a
153 foldl f z (x:xs) = foldl f (f z x) xs
155 foldl1 :: (a -> a -> a) -> [a] -> a
156 foldl1 f (x:xs) = foldl f x xs
157 foldl1 _ [] = errorEmptyList "foldl1"
159 scanl :: (a -> b -> a) -> a -> [b] -> [a]
160 scanl f q ls = q : (case ls of
162 x:xs -> scanl f (f q x) xs)
164 scanl1 :: (a -> a -> a) -> [a] -> [a]
165 scanl1 f (x:xs) = scanl f x xs
166 scanl1 _ [] = errorEmptyList "scanl1"
168 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
171 foldr1 :: (a -> a -> a) -> [a] -> a
173 foldr1 f (x:xs) = f x (foldr1 f xs)
174 foldr1 _ [] = errorEmptyList "foldr1"
176 scanr :: (a -> b -> b) -> b -> [a] -> [b]
178 scanr f q0 (x:xs) = f x q : qs
179 where qs@(q:_) = scanr f q0 xs
181 scanr1 :: (a -> a -> a) -> [a] -> [a]
183 scanr1 f (x:xs) = f x q : qs
184 where qs@(q:_) = scanr1 f xs
185 scanr1 _ [] = errorEmptyList "scanr1"
187 -- iterate f x returns an infinite list of repeated applications of f to x:
188 -- iterate f x == [x, f x, f (f x), ...]
189 iterate :: (a -> a) -> a -> [a]
190 iterate = iterateList
192 iterateFB c f x = x `c` iterateFB c f (f x)
194 iterateList f x = x : iterateList f (f x)
197 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
198 "iterateFB" iterateFB (:) = iterateList
202 -- repeat x is an infinite list, with x the value of every element.
206 repeatFB c x = xs where xs = x `c` xs
207 repeatList x = xs where xs = x : xs
210 "repeat" forall x. repeat x = build (\c _n -> repeatFB c x)
211 "repeatFB" repeatFB (:) = repeatList
214 -- replicate n x is a list of length n with x the value of every element
215 replicate :: Int -> a -> [a]
216 replicate n x = take n (repeat x)
218 -- cycle ties a finite list into a circular one, or equivalently,
219 -- the infinite repetition of the original list. It is the identity
220 -- on infinite lists.
223 cycle [] = error "Prelude.cycle: empty list"
224 cycle xs = xs' where xs' = xs ++ xs'
226 -- takeWhile, applied to a predicate p and a list xs, returns the longest
227 -- prefix (possibly empty) of xs of elements that satisfy p. dropWhile p xs
228 -- returns the remaining suffix. Span p xs is equivalent to
229 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
231 takeWhile :: (a -> Bool) -> [a] -> [a]
234 | p x = x : takeWhile p xs
237 dropWhile :: (a -> Bool) -> [a] -> [a]
239 dropWhile p xs@(x:xs')
240 | p x = dropWhile p xs'
243 -- take n, applied to a list xs, returns the prefix of xs of length n,
244 -- or xs itself if n > length xs. drop n xs returns the suffix of xs
245 -- after the first n elements, or [] if n > length xs. splitAt n xs
246 -- is equivalent to (take n xs, drop n xs).
247 #ifdef USE_REPORT_PRELUDE
248 take :: Int -> [a] -> [a]
251 take n (x:xs) | n > 0 = x : take (minusInt n 1) xs
252 take _ _ = errorNegativeIdx "take"
254 drop :: Int -> [a] -> [a]
257 drop n (_:xs) | n > 0 = drop (minusInt n 1) xs
258 drop _ _ = errorNegativeIdx "drop"
261 splitAt :: Int -> [a] -> ([a],[a])
262 splitAt 0 xs = ([],xs)
263 splitAt _ [] = ([],[])
264 splitAt n (x:xs) | n > 0 = (x:xs',xs'') where (xs',xs'') = splitAt (minusInt n 1) xs
265 splitAt _ _ = errorNegativeIdx "splitAt"
267 #else /* hack away */
268 take :: Int -> [b] -> [b]
269 take (I# n#) xs = takeUInt n# xs
271 -- The general code for take, below, checks n <= maxInt
272 -- No need to check for maxInt overflow when specialised
273 -- at type Int or Int# since the Int must be <= maxInt
275 takeUInt :: Int# -> [b] -> [b]
277 | n >=# 0# = take_unsafe_UInt n xs
278 | otherwise = errorNegativeIdx "take"
280 take_unsafe_UInt :: Int# -> [b] -> [b]
281 take_unsafe_UInt 0# _ = []
282 take_unsafe_UInt m ls =
285 (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
287 takeUInt_append :: Int# -> [b] -> [b] -> [b]
288 takeUInt_append n xs rs
289 | n >=# 0# = take_unsafe_UInt_append n xs rs
290 | otherwise = errorNegativeIdx "take"
292 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
293 take_unsafe_UInt_append 0# _ rs = rs
294 take_unsafe_UInt_append m ls rs =
297 (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
299 drop :: Int -> [b] -> [b]
301 | n# <# 0# = errorNegativeIdx "drop"
302 | otherwise = drop# n# ls
304 drop# :: Int# -> [a] -> [a]
307 drop# m# (_:xs) = drop# (m# -# 1#) xs
309 splitAt :: Int -> [b] -> ([b], [b])
311 | n# <# 0# = errorNegativeIdx "splitAt"
312 | otherwise = splitAt# n# ls
314 splitAt# :: Int# -> [a] -> ([a], [a])
315 splitAt# 0# xs = ([], xs)
316 splitAt# _ xs@[] = (xs, xs)
317 splitAt# m# (x:xs) = (x:xs', xs'')
319 (xs', xs'') = splitAt# (m# -# 1#) xs
321 #endif /* USE_REPORT_PRELUDE */
323 span, break :: (a -> Bool) -> [a] -> ([a],[a])
324 span _ xs@[] = (xs, xs)
326 | p x = let (ys,zs) = span p xs' in (x:ys,zs)
327 | otherwise = ([],xs)
329 #ifdef USE_REPORT_PRELUDE
330 break p = span (not . p)
332 -- HBC version (stolen)
333 break _ xs@[] = (xs, xs)
336 | otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
339 -- reverse xs returns the elements of xs in reverse order. xs must be finite.
340 reverse :: [a] -> [a]
341 #ifdef USE_REPORT_PRELUDE
342 reverse = foldl (flip (:)) []
347 rev (x:xs) a = rev xs (x:a)
350 -- and returns the conjunction of a Boolean list. For the result to be
351 -- True, the list must be finite; False, however, results from a False
352 -- value at a finite index of a finite or infinite list. or is the
353 -- disjunctive dual of and.
354 and, or :: [Bool] -> Bool
355 #ifdef USE_REPORT_PRELUDE
356 and = foldr (&&) True
357 or = foldr (||) False
360 and (x:xs) = x && and xs
362 or (x:xs) = x || or xs
365 "and/build" forall (g::forall b.(Bool->b->b)->b->b) .
366 and (build g) = g (&&) True
367 "or/build" forall (g::forall b.(Bool->b->b)->b->b) .
368 or (build g) = g (||) False
372 -- Applied to a predicate and a list, any determines if any element
373 -- of the list satisfies the predicate. Similarly, for all.
374 any, all :: (a -> Bool) -> [a] -> Bool
375 #ifdef USE_REPORT_PRELUDE
380 any p (x:xs) = p x || any p xs
383 all p (x:xs) = p x && all p xs
385 "any/build" forall p (g::forall b.(a->b->b)->b->b) .
386 any p (build g) = g ((||) . p) False
387 "all/build" forall p (g::forall b.(a->b->b)->b->b) .
388 all p (build g) = g ((&&) . p) True
392 -- elem is the list membership predicate, usually written in infix form,
393 -- e.g., x `elem` xs. notElem is the negation.
394 elem, notElem :: (Eq a) => a -> [a] -> Bool
395 #ifdef USE_REPORT_PRELUDE
397 notElem x = all (/= x)
400 elem x (y:ys) = x==y || elem x ys
403 notElem x (y:ys)= x /= y && notElem x ys
406 -- lookup key assocs looks up a key in an association list.
407 lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
408 lookup _key [] = Nothing
409 lookup key ((x,y):xys)
411 | otherwise = lookup key xys
414 -- maximum and minimum return the maximum or minimum value from a list,
415 -- which must be non-empty, finite, and of an ordered type.
416 {-# SPECIALISE maximum :: [Int] -> Int #-}
417 {-# SPECIALISE minimum :: [Int] -> Int #-}
418 maximum, minimum :: (Ord a) => [a] -> a
419 maximum [] = errorEmptyList "maximum"
420 maximum xs = foldl1 max xs
422 minimum [] = errorEmptyList "minimum"
423 minimum xs = foldl1 min xs
425 concatMap :: (a -> [b]) -> [a] -> [b]
426 concatMap f = foldr ((++) . f) []
428 concat :: [[a]] -> [a]
429 {-# INLINE concat #-}
430 concat = foldr (++) []
435 -- List index (subscript) operator, 0-origin
436 (!!) :: [a] -> Int -> a
437 #ifdef USE_REPORT_PRELUDE
439 (_:xs) !! n | n > 0 = xs !! (minusInt n 1)
440 (_:_) !! _ = error "Prelude.(!!): negative index"
441 [] !! _ = error "Prelude.(!!): index too large"
443 -- HBC version (stolen), then unboxified
444 -- The semantics is not quite the same for error conditions
445 -- in the more efficient version.
447 xs !! (I# n) | n <# 0# = error "Prelude.(!!): negative index\n"
448 | otherwise = sub xs n
450 sub :: [a] -> Int# -> a
451 sub [] _ = error "Prelude.(!!): index too large\n"
452 sub (y:ys) n = if n ==# 0#
454 else sub ys (n -# 1#)
459 %*********************************************************
461 \subsection{The zip family}
463 %*********************************************************
466 foldr2 _k z [] _ys = z
467 foldr2 _k z _xs [] = z
468 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
470 foldr2_left _k z _x _r [] = z
471 foldr2_left k _z x r (y:ys) = k x y (r ys)
473 foldr2_right _k z _y _r [] = z
474 foldr2_right k _z y r (x:xs) = k x y (r xs)
476 -- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
477 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
479 "foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
480 foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
482 "foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
483 foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
487 The foldr2/right rule isn't exactly right, because it changes
488 the strictness of foldr2 (and thereby zip)
490 E.g. main = print (null (zip nonobviousNil (build undefined)))
491 where nonobviousNil = f 3
492 f n = if n == 0 then [] else f (n-1)
494 I'm going to leave it though.
497 zip takes two lists and returns a list of corresponding pairs. If one
498 input list is short, excess elements of the longer list are discarded.
499 zip3 takes three lists and returns a list of triples. Zips for larger
500 tuples are in the List library
503 ----------------------------------------------
504 zip :: [a] -> [b] -> [(a,b)]
507 zipFB c x y r = (x,y) `c` r
510 zipList :: [a] -> [b] -> [(a,b)]
511 zipList (a:as) (b:bs) = (a,b) : zipList as bs
515 "zip" forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
516 "zipList" foldr2 (zipFB (:)) [] = zipList
521 ----------------------------------------------
522 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
524 -- zip3 = zipWith3 (,,)
525 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
530 -- The zipWith family generalises the zip family by zipping with the
531 -- function given as the first argument, instead of a tupling function.
532 -- For example, zipWith (+) is applied to two lists to produce the list
533 -- of corresponding sums.
537 ----------------------------------------------
538 zipWith :: (a->b->c) -> [a]->[b]->[c]
539 zipWith = zipWithList
542 zipWithFB c f x y r = (x `f` y) `c` r
544 zipWithList :: (a->b->c) -> [a] -> [b] -> [c]
545 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
546 zipWithList _ _ _ = []
549 "zipWith" forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
550 "zipWithList" forall f. foldr2 (zipWithFB (:) f) [] = zipWithList f
555 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
556 zipWith3 z (a:as) (b:bs) (c:cs)
557 = z a b c : zipWith3 z as bs cs
558 zipWith3 _ _ _ _ = []
560 -- unzip transforms a list of pairs into a pair of lists.
561 unzip :: [(a,b)] -> ([a],[b])
563 unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
565 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
566 {-# INLINE unzip3 #-}
567 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
572 %*********************************************************
574 \subsection{Error code}
576 %*********************************************************
578 Common up near identical calls to `error' to reduce the number
579 constant strings created when compiled:
582 errorEmptyList :: String -> a
584 error (prel_list_str ++ fun ++ ": empty list")
586 errorNegativeIdx :: String -> a
587 errorNegativeIdx fun =
588 error (prel_list_str ++ fun ++ ": negative index")
590 prel_list_str :: String
591 prel_list_str = "Prelude."