[project @ 1999-07-14 08:37:57 by simonmar]
[ghc-hetmet.git] / ghc / lib / std / PrelList.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4
5 \section[PrelList]{Module @PrelList@}
6
7 The List data type and its operations
8
9 \begin{code}
10 {-# OPTIONS -fno-implicit-prelude #-}
11
12 module PrelList (
13    [] (..),
14
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,
20    reverse, and, or,
21    any, all, elem, notElem, lookup,
22    maximum, minimum, concatMap,
23    zip, zip3, zipWith, zipWith3, unzip, unzip3,
24
25 #ifdef USE_REPORT_PRELUDE
26
27 #else
28
29    -- non-standard, but hidden when creating the Prelude
30    -- export list.
31    takeUInt_append
32
33 #endif
34
35  ) where
36
37 import {-# SOURCE #-} PrelErr ( error )
38 import PrelTup
39 import PrelMaybe
40 import PrelBase
41
42 infixl 9  !!
43 infix  4 `elem`, `notElem`
44 \end{code}
45
46 %*********************************************************
47 %*                                                      *
48 \subsection{List-manipulation functions}
49 %*                                                      *
50 %*********************************************************
51
52 \begin{code}
53 -- head and tail extract the first element and remaining elements,
54 -- respectively, of a list, which must be non-empty.  last and init
55 -- are the dual functions working from the end of a finite list,
56 -- rather than the beginning.
57
58 head                    :: [a] -> a
59 head (x:_)              =  x
60 head []                 =  badHead
61
62 badHead = errorEmptyList "head"
63
64 -- This rule is useful in cases like 
65 --      head [y | (x,y) <- ps, x==t]
66 {-# RULES
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)
71  #-}
72
73 tail                    :: [a] -> [a]
74 tail (_:xs)             =  xs
75 tail []                 =  errorEmptyList "tail"
76
77 last                    :: [a] -> a
78 #ifdef USE_REPORT_PRELUDE
79 last [x]                =  x
80 last (_:xs)             =  last xs
81 last []                 =  errorEmptyList "last"
82 #else
83 -- eliminate repeated cases
84 last []                 =  errorEmptyList "last"
85 last (x:xs)             =  last' x xs
86   where last' y []     = y
87         last' _ (y:ys) = last' y ys
88 #endif
89
90 init                    :: [a] -> [a]
91 #ifdef USE_REPORT_PRELUDE
92 init [x]                =  []
93 init (x:xs)             =  x : init xs
94 init []                 =  errorEmptyList "init"
95 #else
96 -- eliminate repeated cases
97 init []                 =  errorEmptyList "init"
98 init (x:xs)             =  init' x xs
99   where init' _ []     = []
100         init' y (z:zs) = y : init' z zs
101 #endif
102
103 null                    :: [a] -> Bool
104 null []                 =  True
105 null (_:_)              =  False
106
107 -- length returns the length of a finite list as an Int; it is an instance
108 -- of the more general genericLength, the result type of which may be
109 -- any kind of number.
110 length                  :: [a] -> Int
111 length l                =  len l 0#
112   where
113     len :: [a] -> Int# -> Int
114     len []     a# = I# a#
115     len (_:xs) a# = len xs (a# +# 1#)
116
117 -- filter, applied to a predicate and a list, returns the list of those
118 -- elements that satisfy the predicate; i.e.,
119 -- filter p xs = [ x | x <- xs, p x]
120 filter :: (a -> Bool) -> [a] -> [a]
121 {-# INLINE filter #-}
122 filter p xs = build (\c n -> foldr (filterFB c p) n xs)
123
124 filterFB c p x r | p x       = x `c` r
125                  | otherwise = r
126
127 {-# RULES
128 "filterFB"      forall c,p,q.   filterFB (filterFB c p) q = filterFB c (\x -> p x && q x)
129 "filterList"    forall p.       foldr (filterFB (:) p) [] = filterList p
130  #-}
131
132 filterList :: (a -> Bool) -> [a] -> [a]
133 filterList _pred []    = []
134 filterList pred (x:xs)
135   | pred x         = x : filterList pred xs
136   | otherwise      = filterList pred xs
137
138 -- foldl, applied to a binary operator, a starting value (typically the
139 -- left-identity of the operator), and a list, reduces the list using
140 -- the binary operator, from left to right:
141 --  foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
142 -- foldl1 is a variant that has no starting value argument, and  thus must
143 -- be applied to non-empty lists.  scanl is similar to foldl, but returns
144 -- a list of successive reduced values from the left:
145 --      scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
146 -- Note that  last (scanl f z xs) == foldl f z xs.
147 -- scanl1 is similar, again without the starting element:
148 --      scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
149
150 foldl                   :: (a -> b -> a) -> a -> [b] -> a
151 foldl _ z []            =  z
152 foldl f z (x:xs)        =  foldl f (f z x) xs
153
154 foldl1                  :: (a -> a -> a) -> [a] -> a
155 foldl1 f (x:xs)         =  foldl f x xs
156 foldl1 _ []             =  errorEmptyList "foldl1"
157
158 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
159 scanl f q ls            =  q : (case ls of
160                                 []   -> []
161                                 x:xs -> scanl f (f q x) xs)
162
163 scanl1                  :: (a -> a -> a) -> [a] -> [a]
164 scanl1 f (x:xs)         =  scanl f x xs
165 scanl1 _ []             =  errorEmptyList "scanl1"
166
167 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
168 -- above functions.
169
170 foldr1                  :: (a -> a -> a) -> [a] -> a
171 foldr1 _ [x]            =  x
172 foldr1 f (x:xs)         =  f x (foldr1 f xs)
173 foldr1 _ []             =  errorEmptyList "foldr1"
174
175 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
176 scanr _ q0 []           =  [q0]
177 scanr f q0 (x:xs)       =  f x q : qs
178                            where qs@(q:_) = scanr f q0 xs 
179
180 scanr1                  :: (a -> a -> a) -> [a] -> [a]
181 scanr1 _  [x]           =  [x]
182 scanr1 f  (x:xs)        =  f x q : qs
183                            where qs@(q:_) = scanr1 f xs 
184 scanr1 _ []             =  errorEmptyList "scanr1"
185
186 -- iterate f x returns an infinite list of repeated applications of f to x:
187 -- iterate f x == [x, f x, f (f x), ...]
188 iterate :: (a -> a) -> a -> [a]
189 {-# INLINE iterate #-}
190 iterate f x = build (\c _n -> iterateFB c f x)
191
192 iterateFB c f x = x `c` iterateFB c f (f x)
193
194 iterateList f x =  x : iterateList f (f x)
195
196 {-# RULES
197 "iterate"       iterateFB (:) = iterateList
198  #-}
199
200
201 -- repeat x is an infinite list, with x the value of every element.
202 repeat :: a -> [a]
203 {-# INLINE repeat #-}
204 repeat x = build (\c _n -> repeatFB c x)
205
206 repeatFB c x = xs where xs = x `c` xs
207 repeatList x = xs where xs = x :   xs
208
209 {-# RULES
210 "repeat"        repeatFB (:) = repeatList
211  #-}
212
213 -- replicate n x is a list of length n with x the value of every element
214 replicate               :: Int -> a -> [a]
215 replicate n x           =  take n (repeat x)
216
217 -- cycle ties a finite list into a circular one, or equivalently,
218 -- the infinite repetition of the original list.  It is the identity
219 -- on infinite lists.
220
221 cycle                   :: [a] -> [a]
222 cycle []                = error "Prelude.cycle: empty list"
223 cycle xs                = xs' where xs' = xs ++ xs'
224
225 -- takeWhile, applied to a predicate p and a list xs, returns the longest
226 -- prefix (possibly empty) of xs of elements that satisfy p.  dropWhile p xs
227 -- returns the remaining suffix.  Span p xs is equivalent to 
228 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
229
230 takeWhile               :: (a -> Bool) -> [a] -> [a]
231 takeWhile _ []          =  []
232 takeWhile p (x:xs) 
233             | p x       =  x : takeWhile p xs
234             | otherwise =  []
235
236 dropWhile               :: (a -> Bool) -> [a] -> [a]
237 dropWhile _ []          =  []
238 dropWhile p xs@(x:xs')
239             | p x       =  dropWhile p xs'
240             | otherwise =  xs
241
242 -- take n, applied to a list xs, returns the prefix of xs of length n,
243 -- or xs itself if n > length xs.  drop n xs returns the suffix of xs
244 -- after the first n elements, or [] if n > length xs.  splitAt n xs
245 -- is equivalent to (take n xs, drop n xs).
246 #ifdef USE_REPORT_PRELUDE
247 take                   :: Int -> [a] -> [a]
248 take 0 _               =  []
249 take _ []              =  []
250 take n (x:xs) | n > 0  =  x : take (minusInt n 1) xs
251 take _     _           =  errorNegativeIdx "take"
252
253 drop                   :: Int -> [a] -> [a]
254 drop 0 xs              =  xs
255 drop _ []              =  []
256 drop n (_:xs) | n > 0  =  drop (minusInt n 1) xs
257 drop _     _           =  errorNegativeIdx "drop"
258
259
260 splitAt                   :: Int -> [a] -> ([a],[a])
261 splitAt 0 xs              =  ([],xs)
262 splitAt _ []              =  ([],[])
263 splitAt n (x:xs) | n > 0  =  (x:xs',xs'') where (xs',xs'') = splitAt (minusInt n 1) xs
264 splitAt _     _           =  errorNegativeIdx "splitAt"
265
266 #else /* hack away */
267 take    :: Int -> [b] -> [b]
268 take (I# n#) xs = takeUInt n# xs
269
270 -- The general code for take, below, checks n <= maxInt
271 -- No need to check for maxInt overflow when specialised
272 -- at type Int or Int# since the Int must be <= maxInt
273
274 takeUInt :: Int# -> [b] -> [b]
275 takeUInt n xs
276   | n >=# 0#  =  take_unsafe_UInt n xs
277   | otherwise =  errorNegativeIdx "take"
278
279 take_unsafe_UInt :: Int# -> [b] -> [b]
280 take_unsafe_UInt 0#  _  = []
281 take_unsafe_UInt m   ls =
282   case ls of
283     []     -> []
284     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
285
286 takeUInt_append :: Int# -> [b] -> [b] -> [b]
287 takeUInt_append n xs rs
288   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
289   | otherwise =  errorNegativeIdx "take"
290
291 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
292 take_unsafe_UInt_append 0#  _ rs  = rs
293 take_unsafe_UInt_append m  ls rs  =
294   case ls of
295     []     -> rs
296     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
297
298 drop            :: Int -> [b] -> [b]
299 drop (I# n#) ls
300   | n# <# 0#    = errorNegativeIdx "drop"
301   | otherwise   = drop# n# ls
302     where
303         drop# :: Int# -> [a] -> [a]
304         drop# 0# xs      = xs
305         drop# _  xs@[]   = xs
306         drop# m# (_:xs)  = drop# (m# -# 1#) xs
307
308 splitAt :: Int -> [b] -> ([b], [b])
309 splitAt (I# n#) ls
310   | n# <# 0#    = errorNegativeIdx "splitAt"
311   | otherwise   = splitAt# n# ls
312     where
313         splitAt# :: Int# -> [a] -> ([a], [a])
314         splitAt# 0# xs     = ([], xs)
315         splitAt# _  xs@[]  = (xs, xs)
316         splitAt# m# (x:xs) = (x:xs', xs'')
317           where
318             (xs', xs'') = splitAt# (m# -# 1#) xs
319
320 #endif /* USE_REPORT_PRELUDE */
321
322 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
323 span _ xs@[]            =  (xs, xs)
324 span p xs@(x:xs')
325          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
326          | otherwise    =  ([],xs)
327
328 #ifdef USE_REPORT_PRELUDE
329 break p                 =  span (not . p)
330 #else
331 -- HBC version (stolen)
332 break _ xs@[]           =  (xs, xs)
333 break p xs@(x:xs')
334            | p x        =  ([],xs)
335            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
336 #endif
337
338 -- reverse xs returns the elements of xs in reverse order.  xs must be finite.
339 reverse                 :: [a] -> [a]
340 #ifdef USE_REPORT_PRELUDE
341 reverse                 =  foldl (flip (:)) []
342 #else
343 reverse l =  rev l []
344   where
345     rev []     a = a
346     rev (x:xs) a = rev xs (x:a)
347 #endif
348
349 -- and returns the conjunction of a Boolean list.  For the result to be
350 -- True, the list must be finite; False, however, results from a False
351 -- value at a finite index of a finite or infinite list.  or is the
352 -- disjunctive dual of and.
353 and, or                 :: [Bool] -> Bool
354 #ifdef USE_REPORT_PRELUDE
355 and                     =  foldr (&&) True
356 or                      =  foldr (||) False
357 #else
358 and []          =  True
359 and (x:xs)      =  x && and xs
360 or []           =  False
361 or (x:xs)       =  x || or xs
362
363 {-# RULES
364 "and/build"     forall g::forall b.(Bool->b->b)->b->b . 
365                 and (build g) = g (&&) True
366 "or/build"      forall g::forall b.(Bool->b->b)->b->b . 
367                 or (build g) = g (||) False
368  #-}
369 #endif
370
371 -- Applied to a predicate and a list, any determines if any element
372 -- of the list satisfies the predicate.  Similarly, for all.
373 any, all                :: (a -> Bool) -> [a] -> Bool
374 #ifdef USE_REPORT_PRELUDE
375 any p                   =  or . map p
376 all p                   =  and . map p
377 #else
378 any _ []        = False
379 any p (x:xs)    = p x || any p xs
380
381 all _ []        =  True
382 all p (x:xs)    =  p x && all p xs
383 {-# RULES
384 "any/build"     forall p, g::forall b.(a->b->b)->b->b . 
385                 any p (build g) = g ((||) . p) False
386 "all/build"     forall p, g::forall b.(a->b->b)->b->b . 
387                 all p (build g) = g ((&&) . p) True
388  #-}
389 #endif
390
391 -- elem is the list membership predicate, usually written in infix form,
392 -- e.g., x `elem` xs.  notElem is the negation.
393 elem, notElem           :: (Eq a) => a -> [a] -> Bool
394 #ifdef USE_REPORT_PRELUDE
395 elem x                  =  any (== x)
396 notElem x               =  all (/= x)
397 #else
398 elem _ []       = False
399 elem x (y:ys)   = x==y || elem x ys
400
401 notElem _ []    =  True
402 notElem x (y:ys)=  x /= y && notElem x ys
403 #endif
404
405 -- lookup key assocs looks up a key in an association list.
406 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
407 lookup _key []          =  Nothing
408 lookup  key ((x,y):xys)
409     | key == x          =  Just y
410     | otherwise         =  lookup key xys
411
412
413 -- maximum and minimum return the maximum or minimum value from a list,
414 -- which must be non-empty, finite, and of an ordered type.
415 {-# SPECIALISE maximum :: [Int] -> Int #-}
416 {-# SPECIALISE minimum :: [Int] -> Int #-}
417 maximum, minimum        :: (Ord a) => [a] -> a
418 maximum []              =  errorEmptyList "maximum"
419 maximum xs              =  foldl1 max xs
420
421 minimum []              =  errorEmptyList "minimum"
422 minimum xs              =  foldl1 min xs
423
424 concatMap               :: (a -> [b]) -> [a] -> [b]
425 concatMap f             =  foldr ((++) . f) []
426
427 concat :: [[a]] -> [a]
428 {-# INLINE concat #-}
429 concat = foldr (++) []
430 \end{code}
431
432
433 \begin{code}
434 -- List index (subscript) operator, 0-origin
435 (!!)                    :: [a] -> Int -> a
436 #ifdef USE_REPORT_PRELUDE
437 (x:_)  !! 0             =  x
438 (_:xs) !! n | n > 0     =  xs !! (minusInt n 1)
439 (_:_)  !! _             =  error "Prelude.(!!): negative index"
440 []     !! _             =  error "Prelude.(!!): index too large"
441 #else
442 -- HBC version (stolen), then unboxified
443 -- The semantics is not quite the same for error conditions
444 -- in the more efficient version.
445 --
446 xs !! (I# n) | n <# 0#   =  error "Prelude.(!!): negative index\n"
447              | otherwise =  sub xs n
448                          where
449                             sub :: [a] -> Int# -> a
450                             sub []     _ = error "Prelude.(!!): index too large\n"
451                             sub (y:ys) n = if n ==# 0#
452                                            then y
453                                            else sub ys (n -# 1#)
454 #endif
455 \end{code}
456
457
458 %*********************************************************
459 %*                                                      *
460 \subsection{The zip family}
461 %*                                                      *
462 %*********************************************************
463
464 \begin{code}
465 foldr2 _k z []    _ys    = z
466 foldr2 _k z _xs   []     = z
467 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
468
469 foldr2_left _k  z _x _r []     = z
470 foldr2_left  k _z  x  r (y:ys) = k x y (r ys)
471
472 foldr2_right _k z  _y _r []     = z
473 foldr2_right  k _z  y  r (x:xs) = k x y (r xs)
474
475 -- foldr2 k z xs ys = foldr (foldr2_left k z)  (\_ -> z) xs ys
476 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
477 {-# RULES
478 "foldr2/left"   forall k,z,ys,g::forall b.(a->b->b)->b->b . 
479                   foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys
480
481 "foldr2/right"  forall k,z,xs,g::forall b.(a->b->b)->b->b . 
482                   foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
483  #-}
484 \end{code}
485
486 zip takes two lists and returns a list of corresponding pairs.  If one
487 input list is short, excess elements of the longer list are discarded.
488 zip3 takes three lists and returns a list of triples.  Zips for larger
489 tuples are in the List library
490
491 \begin{code}
492 ----------------------------------------------
493 zip :: [a] -> [b] -> [(a,b)]
494 {-# INLINE zip #-}
495 zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
496
497 zipFB c x y r = (x,y) `c` r
498
499
500 zipList               :: [a] -> [b] -> [(a,b)]
501 zipList (a:as) (b:bs) = (a,b) : zipList as bs
502 zipList _      _      = []
503
504 {-# RULES
505 "zipList"       foldr2 (zipFB (:)) [] = zipList
506  #-}
507 \end{code}
508
509 \begin{code}
510 ----------------------------------------------
511 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
512 -- Specification
513 -- zip3 =  zipWith3 (,,)
514 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
515 zip3 _      _      _      = []
516 \end{code}
517
518
519 -- The zipWith family generalises the zip family by zipping with the
520 -- function given as the first argument, instead of a tupling function.
521 -- For example, zipWith (+) is applied to two lists to produce the list
522 -- of corresponding sums.
523
524
525 \begin{code}
526 ----------------------------------------------
527 zipWith :: (a->b->c) -> [a]->[b]->[c]
528 {-# INLINE zipWith #-}
529 zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
530
531 zipWithFB c f x y r = (x `f` y) `c` r
532
533 zipWithList                 :: (a->b->c) -> [a] -> [b] -> [c]
534 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
535 zipWithList _ _      _      = []
536
537 {-# RULES
538 "zipWithList"   forall f. foldr2 (zipWithFB (:) f) [] = zipWithList f
539   #-}
540 \end{code}
541
542 \begin{code}
543 zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]
544 zipWith3 z (a:as) (b:bs) (c:cs)
545                         =  z a b c : zipWith3 z as bs cs
546 zipWith3 _ _ _ _        =  []
547
548 -- unzip transforms a list of pairs into a pair of lists.  
549 unzip    :: [(a,b)] -> ([a],[b])
550 {-# INLINE unzip #-}
551 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
552
553 unzip3   :: [(a,b,c)] -> ([a],[b],[c])
554 {-# INLINE unzip3 #-}
555 unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
556                   ([],[],[])
557 \end{code}
558
559
560 %*********************************************************
561 %*                                                      *
562 \subsection{Error code}
563 %*                                                      *
564 %*********************************************************
565
566 Common up near identical calls to `error' to reduce the number
567 constant strings created when compiled:
568
569 \begin{code}
570 errorEmptyList :: String -> a
571 errorEmptyList fun =
572   error (prel_list_str ++ fun ++ ": empty list")
573
574 errorNegativeIdx :: String -> a
575 errorNegativeIdx fun =
576  error (prel_list_str ++ fun ++ ": negative index")
577
578 prel_list_str :: String
579 prel_list_str = "Prelude."
580 \end{code}