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