[project @ 2000-06-30 13:39:35 by simonmar]
[ghc-hetmet.git] / ghc / lib / std / PrelList.lhs
1 % ------------------------------------------------------------------------------
2 % $Id: PrelList.lhs,v 1.20 2000/06/30 13:39:35 simonmar Exp $
3 %
4 % (c) The University of Glasgow, 1994-2000
5 %
6
7 \section[PrelList]{Module @PrelList@}
8
9 The List data type and its operations
10
11 \begin{code}
12 {-# OPTIONS -fno-implicit-prelude #-}
13
14 module PrelList (
15    [] (..),
16
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,
22    reverse, and, or,
23    any, all, elem, notElem, lookup,
24    maximum, minimum, concatMap,
25    zip, zip3, zipWith, zipWith3, unzip, unzip3,
26 #ifdef USE_REPORT_PRELUDE
27
28 #else
29
30    -- non-standard, but hidden when creating the Prelude
31    -- export list.
32    takeUInt_append
33
34 #endif
35
36  ) where
37
38 import {-# SOURCE #-} PrelErr ( error )
39 import PrelTup
40 import PrelMaybe
41 import PrelBase
42
43 infixl 9  !!
44 infix  4 `elem`, `notElem`
45 \end{code}
46
47 %*********************************************************
48 %*                                                      *
49 \subsection{List-manipulation functions}
50 %*                                                      *
51 %*********************************************************
52
53 \begin{code}
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.
58
59 head                    :: [a] -> a
60 head (x:_)              =  x
61 head []                 =  badHead
62
63 badHead = errorEmptyList "head"
64
65 -- This rule is useful in cases like 
66 --      head [y | (x,y) <- ps, x==t]
67 {-# RULES
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)
72  #-}
73
74 tail                    :: [a] -> [a]
75 tail (_:xs)             =  xs
76 tail []                 =  errorEmptyList "tail"
77
78 last                    :: [a] -> a
79 #ifdef USE_REPORT_PRELUDE
80 last [x]                =  x
81 last (_:xs)             =  last xs
82 last []                 =  errorEmptyList "last"
83 #else
84 -- eliminate repeated cases
85 last []                 =  errorEmptyList "last"
86 last (x:xs)             =  last' x xs
87   where last' y []     = y
88         last' _ (y:ys) = last' y ys
89 #endif
90
91 init                    :: [a] -> [a]
92 #ifdef USE_REPORT_PRELUDE
93 init [x]                =  []
94 init (x:xs)             =  x : init xs
95 init []                 =  errorEmptyList "init"
96 #else
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
102 #endif
103
104 null                    :: [a] -> Bool
105 null []                 =  True
106 null (_:_)              =  False
107
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.
111 length                  :: [a] -> Int
112 length l                =  len l 0#
113   where
114     len :: [a] -> Int# -> Int
115     len []     a# = I# a#
116     len (_:xs) a# = len xs (a# +# 1#)
117
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]
122 filter = filterList
123
124 filterFB c p x r | p x       = x `c` r
125                  | otherwise = r
126
127 {-# RULES
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
131  #-}
132
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
138
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, ...]
150
151 foldl                   :: (a -> b -> a) -> a -> [b] -> a
152 foldl _ z []            =  z
153 foldl f z (x:xs)        =  foldl f (f z x) xs
154
155 foldl1                  :: (a -> a -> a) -> [a] -> a
156 foldl1 f (x:xs)         =  foldl f x xs
157 foldl1 _ []             =  errorEmptyList "foldl1"
158
159 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
160 scanl f q ls            =  q : (case ls of
161                                 []   -> []
162                                 x:xs -> scanl f (f q x) xs)
163
164 scanl1                  :: (a -> a -> a) -> [a] -> [a]
165 scanl1 f (x:xs)         =  scanl f x xs
166 scanl1 _ []             =  errorEmptyList "scanl1"
167
168 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
169 -- above functions.
170
171 foldr1                  :: (a -> a -> a) -> [a] -> a
172 foldr1 _ [x]            =  x
173 foldr1 f (x:xs)         =  f x (foldr1 f xs)
174 foldr1 _ []             =  errorEmptyList "foldr1"
175
176 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
177 scanr _ q0 []           =  [q0]
178 scanr f q0 (x:xs)       =  f x q : qs
179                            where qs@(q:_) = scanr f q0 xs 
180
181 scanr1                  :: (a -> a -> a) -> [a] -> [a]
182 scanr1 _  [x]           =  [x]
183 scanr1 f  (x:xs)        =  f x q : qs
184                            where qs@(q:_) = scanr1 f xs 
185 scanr1 _ []             =  errorEmptyList "scanr1"
186
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
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"       forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
198 "iterateFB"                     iterateFB (:) = iterateList
199  #-}
200
201
202 -- repeat x is an infinite list, with x the value of every element.
203 repeat :: a -> [a]
204 repeat = repeatList
205
206 repeatFB c x = xs where xs = x `c` xs
207 repeatList x = xs where xs = x :   xs
208
209 {-# RULES
210 "repeat"        forall x. repeat x      = build (\c _n -> repeatFB c x)
211 "repeatFB"                repeatFB (:)  = repeatList
212  #-}
213
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)
217
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.
221
222 cycle                   :: [a] -> [a]
223 cycle []                = error "Prelude.cycle: empty list"
224 cycle xs                = xs' where xs' = xs ++ xs'
225
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.
230
231 takeWhile               :: (a -> Bool) -> [a] -> [a]
232 takeWhile _ []          =  []
233 takeWhile p (x:xs) 
234             | p x       =  x : takeWhile p xs
235             | otherwise =  []
236
237 dropWhile               :: (a -> Bool) -> [a] -> [a]
238 dropWhile _ []          =  []
239 dropWhile p xs@(x:xs')
240             | p x       =  dropWhile p xs'
241             | otherwise =  xs
242
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]
249 take 0 _               =  []
250 take _ []              =  []
251 take n (x:xs) | n > 0  =  x : take (minusInt n 1) xs
252 take _     _           =  errorNegativeIdx "take"
253
254 drop                   :: Int -> [a] -> [a]
255 drop 0 xs              =  xs
256 drop _ []              =  []
257 drop n (_:xs) | n > 0  =  drop (minusInt n 1) xs
258 drop _     _           =  errorNegativeIdx "drop"
259
260
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"
266
267 #else /* hack away */
268 take    :: Int -> [b] -> [b]
269 take (I# n#) xs = takeUInt n# xs
270
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
274
275 takeUInt :: Int# -> [b] -> [b]
276 takeUInt n xs
277   | n >=# 0#  =  take_unsafe_UInt n xs
278   | otherwise =  errorNegativeIdx "take"
279
280 take_unsafe_UInt :: Int# -> [b] -> [b]
281 take_unsafe_UInt 0#  _  = []
282 take_unsafe_UInt m   ls =
283   case ls of
284     []     -> []
285     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
286
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"
291
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  =
295   case ls of
296     []     -> rs
297     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
298
299 drop            :: Int -> [b] -> [b]
300 drop (I# n#) ls
301   | n# <# 0#    = errorNegativeIdx "drop"
302   | otherwise   = drop# n# ls
303     where
304         drop# :: Int# -> [a] -> [a]
305         drop# 0# xs      = xs
306         drop# _  xs@[]   = xs
307         drop# m# (_:xs)  = drop# (m# -# 1#) xs
308
309 splitAt :: Int -> [b] -> ([b], [b])
310 splitAt (I# n#) ls
311   | n# <# 0#    = errorNegativeIdx "splitAt"
312   | otherwise   = splitAt# n# ls
313     where
314         splitAt# :: Int# -> [a] -> ([a], [a])
315         splitAt# 0# xs     = ([], xs)
316         splitAt# _  xs@[]  = (xs, xs)
317         splitAt# m# (x:xs) = (x:xs', xs'')
318           where
319             (xs', xs'') = splitAt# (m# -# 1#) xs
320
321 #endif /* USE_REPORT_PRELUDE */
322
323 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
324 span _ xs@[]            =  (xs, xs)
325 span p xs@(x:xs')
326          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
327          | otherwise    =  ([],xs)
328
329 #ifdef USE_REPORT_PRELUDE
330 break p                 =  span (not . p)
331 #else
332 -- HBC version (stolen)
333 break _ xs@[]           =  (xs, xs)
334 break p xs@(x:xs')
335            | p x        =  ([],xs)
336            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
337 #endif
338
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 (:)) []
343 #else
344 reverse l =  rev l []
345   where
346     rev []     a = a
347     rev (x:xs) a = rev xs (x:a)
348 #endif
349
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
358 #else
359 and []          =  True
360 and (x:xs)      =  x && and xs
361 or []           =  False
362 or (x:xs)       =  x || or xs
363
364 {-# RULES
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
369  #-}
370 #endif
371
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
376 any p                   =  or . map p
377 all p                   =  and . map p
378 #else
379 any _ []        = False
380 any p (x:xs)    = p x || any p xs
381
382 all _ []        =  True
383 all p (x:xs)    =  p x && all p xs
384 {-# RULES
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
389  #-}
390 #endif
391
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
396 elem x                  =  any (== x)
397 notElem x               =  all (/= x)
398 #else
399 elem _ []       = False
400 elem x (y:ys)   = x==y || elem x ys
401
402 notElem _ []    =  True
403 notElem x (y:ys)=  x /= y && notElem x ys
404 #endif
405
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)
410     | key == x          =  Just y
411     | otherwise         =  lookup key xys
412
413
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
421
422 minimum []              =  errorEmptyList "minimum"
423 minimum xs              =  foldl1 min xs
424
425 concatMap               :: (a -> [b]) -> [a] -> [b]
426 concatMap f             =  foldr ((++) . f) []
427
428 concat :: [[a]] -> [a]
429 {-# INLINE concat #-}
430 concat = foldr (++) []
431 \end{code}
432
433
434 \begin{code}
435 -- List index (subscript) operator, 0-origin
436 (!!)                    :: [a] -> Int -> a
437 #ifdef USE_REPORT_PRELUDE
438 (x:_)  !! 0             =  x
439 (_:xs) !! n | n > 0     =  xs !! (minusInt n 1)
440 (_:_)  !! _             =  error "Prelude.(!!): negative index"
441 []     !! _             =  error "Prelude.(!!): index too large"
442 #else
443 -- HBC version (stolen), then unboxified
444 -- The semantics is not quite the same for error conditions
445 -- in the more efficient version.
446 --
447 xs !! (I# n) | n <# 0#   =  error "Prelude.(!!): negative index\n"
448              | otherwise =  sub xs n
449                          where
450                             sub :: [a] -> Int# -> a
451                             sub []     _ = error "Prelude.(!!): index too large\n"
452                             sub (y:ys) n = if n ==# 0#
453                                            then y
454                                            else sub ys (n -# 1#)
455 #endif
456 \end{code}
457
458
459 %*********************************************************
460 %*                                                      *
461 \subsection{The zip family}
462 %*                                                      *
463 %*********************************************************
464
465 \begin{code}
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)
469
470 foldr2_left _k  z _x _r []     = z
471 foldr2_left  k _z  x  r (y:ys) = k x y (r ys)
472
473 foldr2_right _k z  _y _r []     = z
474 foldr2_right  k _z  y  r (x:xs) = k x y (r xs)
475
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
478 {-# RULES
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
481
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
484  #-}
485 \end{code}
486
487 The foldr2/right rule isn't exactly right, because it changes
488 the strictness of foldr2 (and thereby zip)
489
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)
493
494 I'm going to leave it though.
495
496
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
501
502 \begin{code}
503 ----------------------------------------------
504 zip :: [a] -> [b] -> [(a,b)]
505 zip = zipList
506
507 zipFB c x y r = (x,y) `c` r
508
509
510 zipList               :: [a] -> [b] -> [(a,b)]
511 zipList (a:as) (b:bs) = (a,b) : zipList as bs
512 zipList _      _      = []
513
514 {-# RULES
515 "zip"           forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
516 "zipList"       foldr2 (zipFB (:)) []   = zipList
517  #-}
518 \end{code}
519
520 \begin{code}
521 ----------------------------------------------
522 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
523 -- Specification
524 -- zip3 =  zipWith3 (,,)
525 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
526 zip3 _      _      _      = []
527 \end{code}
528
529
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.
534
535
536 \begin{code}
537 ----------------------------------------------
538 zipWith :: (a->b->c) -> [a]->[b]->[c]
539 zipWith = zipWithList
540
541
542 zipWithFB c f x y r = (x `f` y) `c` r
543
544 zipWithList                 :: (a->b->c) -> [a] -> [b] -> [c]
545 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
546 zipWithList _ _      _      = []
547
548 {-# RULES
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
551   #-}
552 \end{code}
553
554 \begin{code}
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 _ _ _ _        =  []
559
560 -- unzip transforms a list of pairs into a pair of lists.  
561 unzip    :: [(a,b)] -> ([a],[b])
562 {-# INLINE unzip #-}
563 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
564
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))
568                   ([],[],[])
569 \end{code}
570
571
572 %*********************************************************
573 %*                                                      *
574 \subsection{Error code}
575 %*                                                      *
576 %*********************************************************
577
578 Common up near identical calls to `error' to reduce the number
579 constant strings created when compiled:
580
581 \begin{code}
582 errorEmptyList :: String -> a
583 errorEmptyList fun =
584   error (prel_list_str ++ fun ++ ": empty list")
585
586 errorNegativeIdx :: String -> a
587 errorNegativeIdx fun =
588  error (prel_list_str ++ fun ++ ": negative index")
589
590 prel_list_str :: String
591 prel_list_str = "Prelude."
592 \end{code}