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