[project @ 2000-06-24 17:47:12 by panne]
[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 #ifdef USE_REPORT_PRELUDE
25
26 #else
27
28    -- non-standard, but hidden when creating the Prelude
29    -- export list.
30    takeUInt_append
31
32 #endif
33
34  ) where
35
36 import {-# SOURCE #-} PrelErr ( error )
37 import PrelTup
38 import PrelMaybe
39 import PrelBase
40
41 infixl 9  !!
42 infix  4 `elem`, `notElem`
43 \end{code}
44
45 %*********************************************************
46 %*                                                      *
47 \subsection{List-manipulation functions}
48 %*                                                      *
49 %*********************************************************
50
51 \begin{code}
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.
56
57 head                    :: [a] -> a
58 head (x:_)              =  x
59 head []                 =  badHead
60
61 badHead = errorEmptyList "head"
62
63 -- This rule is useful in cases like 
64 --      head [y | (x,y) <- ps, x==t]
65 {-# RULES
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)
70  #-}
71
72 tail                    :: [a] -> [a]
73 tail (_:xs)             =  xs
74 tail []                 =  errorEmptyList "tail"
75
76 last                    :: [a] -> a
77 #ifdef USE_REPORT_PRELUDE
78 last [x]                =  x
79 last (_:xs)             =  last xs
80 last []                 =  errorEmptyList "last"
81 #else
82 -- eliminate repeated cases
83 last []                 =  errorEmptyList "last"
84 last (x:xs)             =  last' x xs
85   where last' y []     = y
86         last' _ (y:ys) = last' y ys
87 #endif
88
89 init                    :: [a] -> [a]
90 #ifdef USE_REPORT_PRELUDE
91 init [x]                =  []
92 init (x:xs)             =  x : init xs
93 init []                 =  errorEmptyList "init"
94 #else
95 -- eliminate repeated cases
96 init []                 =  errorEmptyList "init"
97 init (x:xs)             =  init' x xs
98   where init' _ []     = []
99         init' y (z:zs) = y : init' z zs
100 #endif
101
102 null                    :: [a] -> Bool
103 null []                 =  True
104 null (_:_)              =  False
105
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.
109 length                  :: [a] -> Int
110 length l                =  len l 0#
111   where
112     len :: [a] -> Int# -> Int
113     len []     a# = I# a#
114     len (_:xs) a# = len xs (a# +# 1#)
115
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]
120 filter = filterList
121
122 filterFB c p x r | p x       = x `c` r
123                  | otherwise = r
124
125 {-# RULES
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
129  #-}
130
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
136
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, ...]
148
149 foldl                   :: (a -> b -> a) -> a -> [b] -> a
150 foldl _ z []            =  z
151 foldl f z (x:xs)        =  foldl f (f z x) xs
152
153 foldl1                  :: (a -> a -> a) -> [a] -> a
154 foldl1 f (x:xs)         =  foldl f x xs
155 foldl1 _ []             =  errorEmptyList "foldl1"
156
157 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
158 scanl f q ls            =  q : (case ls of
159                                 []   -> []
160                                 x:xs -> scanl f (f q x) xs)
161
162 scanl1                  :: (a -> a -> a) -> [a] -> [a]
163 scanl1 f (x:xs)         =  scanl f x xs
164 scanl1 _ []             =  errorEmptyList "scanl1"
165
166 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
167 -- above functions.
168
169 foldr1                  :: (a -> a -> a) -> [a] -> a
170 foldr1 _ [x]            =  x
171 foldr1 f (x:xs)         =  f x (foldr1 f xs)
172 foldr1 _ []             =  errorEmptyList "foldr1"
173
174 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
175 scanr _ q0 []           =  [q0]
176 scanr f q0 (x:xs)       =  f x q : qs
177                            where qs@(q:_) = scanr f q0 xs 
178
179 scanr1                  :: (a -> a -> a) -> [a] -> [a]
180 scanr1 _  [x]           =  [x]
181 scanr1 f  (x:xs)        =  f x q : qs
182                            where qs@(q:_) = scanr1 f xs 
183 scanr1 _ []             =  errorEmptyList "scanr1"
184
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
189
190 iterateFB c f x = x `c` iterateFB c f (f x)
191
192 iterateList f x =  x : iterateList f (f x)
193
194 {-# RULES
195 "iterate"       forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
196 "iterateFB"                     iterateFB (:) = iterateList
197  #-}
198
199
200 -- repeat x is an infinite list, with x the value of every element.
201 repeat :: a -> [a]
202 repeat = repeatList
203
204 repeatFB c x = xs where xs = x `c` xs
205 repeatList x = xs where xs = x :   xs
206
207 {-# RULES
208 "repeat"        forall x. repeat x      = build (\c _n -> repeatFB c x)
209 "repeatFB"                repeatFB (:)  = repeatList
210  #-}
211
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)
215
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.
219
220 cycle                   :: [a] -> [a]
221 cycle []                = error "Prelude.cycle: empty list"
222 cycle xs                = xs' where xs' = xs ++ xs'
223
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.
228
229 takeWhile               :: (a -> Bool) -> [a] -> [a]
230 takeWhile _ []          =  []
231 takeWhile p (x:xs) 
232             | p x       =  x : takeWhile p xs
233             | otherwise =  []
234
235 dropWhile               :: (a -> Bool) -> [a] -> [a]
236 dropWhile _ []          =  []
237 dropWhile p xs@(x:xs')
238             | p x       =  dropWhile p xs'
239             | otherwise =  xs
240
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]
247 take 0 _               =  []
248 take _ []              =  []
249 take n (x:xs) | n > 0  =  x : take (minusInt n 1) xs
250 take _     _           =  errorNegativeIdx "take"
251
252 drop                   :: Int -> [a] -> [a]
253 drop 0 xs              =  xs
254 drop _ []              =  []
255 drop n (_:xs) | n > 0  =  drop (minusInt n 1) xs
256 drop _     _           =  errorNegativeIdx "drop"
257
258
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"
264
265 #else /* hack away */
266 take    :: Int -> [b] -> [b]
267 take (I# n#) xs = takeUInt n# xs
268
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
272
273 takeUInt :: Int# -> [b] -> [b]
274 takeUInt n xs
275   | n >=# 0#  =  take_unsafe_UInt n xs
276   | otherwise =  errorNegativeIdx "take"
277
278 take_unsafe_UInt :: Int# -> [b] -> [b]
279 take_unsafe_UInt 0#  _  = []
280 take_unsafe_UInt m   ls =
281   case ls of
282     []     -> []
283     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
284
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"
289
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  =
293   case ls of
294     []     -> rs
295     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
296
297 drop            :: Int -> [b] -> [b]
298 drop (I# n#) ls
299   | n# <# 0#    = errorNegativeIdx "drop"
300   | otherwise   = drop# n# ls
301     where
302         drop# :: Int# -> [a] -> [a]
303         drop# 0# xs      = xs
304         drop# _  xs@[]   = xs
305         drop# m# (_:xs)  = drop# (m# -# 1#) xs
306
307 splitAt :: Int -> [b] -> ([b], [b])
308 splitAt (I# n#) ls
309   | n# <# 0#    = errorNegativeIdx "splitAt"
310   | otherwise   = splitAt# n# ls
311     where
312         splitAt# :: Int# -> [a] -> ([a], [a])
313         splitAt# 0# xs     = ([], xs)
314         splitAt# _  xs@[]  = (xs, xs)
315         splitAt# m# (x:xs) = (x:xs', xs'')
316           where
317             (xs', xs'') = splitAt# (m# -# 1#) xs
318
319 #endif /* USE_REPORT_PRELUDE */
320
321 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
322 span _ xs@[]            =  (xs, xs)
323 span p xs@(x:xs')
324          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
325          | otherwise    =  ([],xs)
326
327 #ifdef USE_REPORT_PRELUDE
328 break p                 =  span (not . p)
329 #else
330 -- HBC version (stolen)
331 break _ xs@[]           =  (xs, xs)
332 break p xs@(x:xs')
333            | p x        =  ([],xs)
334            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
335 #endif
336
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 (:)) []
341 #else
342 reverse l =  rev l []
343   where
344     rev []     a = a
345     rev (x:xs) a = rev xs (x:a)
346 #endif
347
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
356 #else
357 and []          =  True
358 and (x:xs)      =  x && and xs
359 or []           =  False
360 or (x:xs)       =  x || or xs
361
362 {-# RULES
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
367  #-}
368 #endif
369
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
374 any p                   =  or . map p
375 all p                   =  and . map p
376 #else
377 any _ []        = False
378 any p (x:xs)    = p x || any p xs
379
380 all _ []        =  True
381 all p (x:xs)    =  p x && all p xs
382 {-# RULES
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
387  #-}
388 #endif
389
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
394 elem x                  =  any (== x)
395 notElem x               =  all (/= x)
396 #else
397 elem _ []       = False
398 elem x (y:ys)   = x==y || elem x ys
399
400 notElem _ []    =  True
401 notElem x (y:ys)=  x /= y && notElem x ys
402 #endif
403
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)
408     | key == x          =  Just y
409     | otherwise         =  lookup key xys
410
411
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
419
420 minimum []              =  errorEmptyList "minimum"
421 minimum xs              =  foldl1 min xs
422
423 concatMap               :: (a -> [b]) -> [a] -> [b]
424 concatMap f             =  foldr ((++) . f) []
425
426 concat :: [[a]] -> [a]
427 {-# INLINE concat #-}
428 concat = foldr (++) []
429 \end{code}
430
431
432 \begin{code}
433 -- List index (subscript) operator, 0-origin
434 (!!)                    :: [a] -> Int -> a
435 #ifdef USE_REPORT_PRELUDE
436 (x:_)  !! 0             =  x
437 (_:xs) !! n | n > 0     =  xs !! (minusInt n 1)
438 (_:_)  !! _             =  error "Prelude.(!!): negative index"
439 []     !! _             =  error "Prelude.(!!): index too large"
440 #else
441 -- HBC version (stolen), then unboxified
442 -- The semantics is not quite the same for error conditions
443 -- in the more efficient version.
444 --
445 xs !! (I# n) | n <# 0#   =  error "Prelude.(!!): negative index\n"
446              | otherwise =  sub xs n
447                          where
448                             sub :: [a] -> Int# -> a
449                             sub []     _ = error "Prelude.(!!): index too large\n"
450                             sub (y:ys) n = if n ==# 0#
451                                            then y
452                                            else sub ys (n -# 1#)
453 #endif
454 \end{code}
455
456
457 %*********************************************************
458 %*                                                      *
459 \subsection{The zip family}
460 %*                                                      *
461 %*********************************************************
462
463 \begin{code}
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)
467
468 foldr2_left _k  z _x _r []     = z
469 foldr2_left  k _z  x  r (y:ys) = k x y (r ys)
470
471 foldr2_right _k z  _y _r []     = z
472 foldr2_right  k _z  y  r (x:xs) = k x y (r xs)
473
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
476 {-# RULES
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
479
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
482  #-}
483 \end{code}
484
485 The foldr2/right rule isn't exactly right, because it changes
486 the strictness of foldr2 (and thereby zip)
487
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)
491
492 I'm going to leave it though.
493
494
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
499
500 \begin{code}
501 ----------------------------------------------
502 zip :: [a] -> [b] -> [(a,b)]
503 zip = zipList
504
505 zipFB c x y r = (x,y) `c` r
506
507
508 zipList               :: [a] -> [b] -> [(a,b)]
509 zipList (a:as) (b:bs) = (a,b) : zipList as bs
510 zipList _      _      = []
511
512 {-# RULES
513 "zip"           forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
514 "zipList"       foldr2 (zipFB (:)) []   = zipList
515  #-}
516 \end{code}
517
518 \begin{code}
519 ----------------------------------------------
520 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
521 -- Specification
522 -- zip3 =  zipWith3 (,,)
523 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
524 zip3 _      _      _      = []
525 \end{code}
526
527
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.
532
533
534 \begin{code}
535 ----------------------------------------------
536 zipWith :: (a->b->c) -> [a]->[b]->[c]
537 zipWith = zipWithList
538
539
540 zipWithFB c f x y r = (x `f` y) `c` r
541
542 zipWithList                 :: (a->b->c) -> [a] -> [b] -> [c]
543 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
544 zipWithList _ _      _      = []
545
546 {-# RULES
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
549   #-}
550 \end{code}
551
552 \begin{code}
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 _ _ _ _        =  []
557
558 -- unzip transforms a list of pairs into a pair of lists.  
559 unzip    :: [(a,b)] -> ([a],[b])
560 {-# INLINE unzip #-}
561 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
562
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))
566                   ([],[],[])
567 \end{code}
568
569
570 %*********************************************************
571 %*                                                      *
572 \subsection{Error code}
573 %*                                                      *
574 %*********************************************************
575
576 Common up near identical calls to `error' to reduce the number
577 constant strings created when compiled:
578
579 \begin{code}
580 errorEmptyList :: String -> a
581 errorEmptyList fun =
582   error (prel_list_str ++ fun ++ ": empty list")
583
584 errorNegativeIdx :: String -> a
585 errorNegativeIdx fun =
586  error (prel_list_str ++ fun ++ ": negative index")
587
588 prel_list_str :: String
589 prel_list_str = "Prelude."
590 \end{code}