[project @ 1999-05-28 19:18:52 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 []                 =  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 {-# INLINE iterate #-}
173 iterate f x = build (\c n -> iterateFB c f x)
174
175 iterateFB c f x = x `c` iterateFB c f (f x)
176
177 iterateList f x =  x : iterateList f (f x)
178
179 {-# RULES
180 "iterate"       iterateFB (:) = iterateList
181  #-}
182
183
184 -- repeat x is an infinite list, with x the value of every element.
185 repeat :: a -> [a]
186 {-# INLINE repeat #-}
187 repeat x = build (\c n -> repeatFB c x)
188
189 repeatFB c x = xs where xs = x `c` xs
190 repeatList x = xs where xs = x :   xs
191
192 {-# RULES
193 "repeat"        repeatFB (:) = repeatList
194  #-}
195
196 -- replicate n x is a list of length n with x the value of every element
197 replicate               :: Int -> a -> [a]
198 replicate n x           =  take n (repeat x)
199
200 -- cycle ties a finite list into a circular one, or equivalently,
201 -- the infinite repetition of the original list.  It is the identity
202 -- on infinite lists.
203
204 cycle                   :: [a] -> [a]
205 cycle []                = error "Prelude.cycle: empty list"
206 cycle xs                = xs' where xs' = xs ++ xs'
207
208 -- takeWhile, applied to a predicate p and a list xs, returns the longest
209 -- prefix (possibly empty) of xs of elements that satisfy p.  dropWhile p xs
210 -- returns the remaining suffix.  Span p xs is equivalent to 
211 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
212
213 takeWhile               :: (a -> Bool) -> [a] -> [a]
214 takeWhile _ []          =  []
215 takeWhile p (x:xs) 
216             | p x       =  x : takeWhile p xs
217             | otherwise =  []
218
219 dropWhile               :: (a -> Bool) -> [a] -> [a]
220 dropWhile _ []          =  []
221 dropWhile p xs@(x:xs')
222             | p x       =  dropWhile p xs'
223             | otherwise =  xs
224
225 -- take n, applied to a list xs, returns the prefix of xs of length n,
226 -- or xs itself if n > length xs.  drop n xs returns the suffix of xs
227 -- after the first n elements, or [] if n > length xs.  splitAt n xs
228 -- is equivalent to (take n xs, drop n xs).
229 #ifdef USE_REPORT_PRELUDE
230 take                   :: Int -> [a] -> [a]
231 take 0 _               =  []
232 take _ []              =  []
233 take n (x:xs) | n > 0  =  x : take (n-1) xs
234 take _     _           =  errorNegativeIdx "take"
235
236 drop                   :: Int -> [a] -> [a]
237 drop 0 xs              =  xs
238 drop _ []              =  []
239 drop n (_:xs) | n > 0  =  drop (n-1) xs
240 drop _     _           =  errorNegativeIdx "drop"
241
242
243 splitAt                   :: Int -> [a] -> ([a],[a])
244 splitAt 0 xs              =  ([],xs)
245 splitAt _ []              =  ([],[])
246 splitAt n (x:xs) | n > 0  =  (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
247 splitAt _     _           =  errorNegativeIdx "splitAt"
248
249 #else /* hack away */
250 take    :: Int -> [b] -> [b]
251 take (I# n#) xs = takeUInt n# xs
252
253 -- The general code for take, below, checks n <= maxInt
254 -- No need to check for maxInt overflow when specialised
255 -- at type Int or Int# since the Int must be <= maxInt
256
257 takeUInt :: Int# -> [b] -> [b]
258 takeUInt n xs
259   | n >=# 0#  =  take_unsafe_UInt n xs
260   | otherwise =  errorNegativeIdx "take"
261
262 take_unsafe_UInt :: Int# -> [b] -> [b]
263 take_unsafe_UInt 0#  _  = []
264 take_unsafe_UInt m   ls =
265   case ls of
266     []     -> []
267     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
268
269 takeUInt_append :: Int# -> [b] -> [b] -> [b]
270 takeUInt_append n xs rs
271   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
272   | otherwise =  errorNegativeIdx "take"
273
274 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
275 take_unsafe_UInt_append 0#  _ rs  = rs
276 take_unsafe_UInt_append m  ls rs  =
277   case ls of
278     []     -> rs
279     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
280
281 drop            :: Int -> [b] -> [b]
282 drop (I# n#) ls
283   | n# <# 0#    = errorNegativeIdx "drop"
284   | otherwise   = drop# n# ls
285     where
286         drop# :: Int# -> [a] -> [a]
287         drop# 0# xs      = xs
288         drop# _  xs@[]   = xs
289         drop# m# (_:xs)  = drop# (m# -# 1#) xs
290
291 splitAt :: Int -> [b] -> ([b], [b])
292 splitAt (I# n#) ls
293   | n# <# 0#    = errorNegativeIdx "splitAt"
294   | otherwise   = splitAt# n# ls
295     where
296         splitAt# :: Int# -> [a] -> ([a], [a])
297         splitAt# 0# xs     = ([], xs)
298         splitAt# _  xs@[]  = (xs, xs)
299         splitAt# m# (x:xs) = (x:xs', xs'')
300           where
301             (xs', xs'') = splitAt# (m# -# 1#) xs
302
303 #endif /* USE_REPORT_PRELUDE */
304
305 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
306 span _ xs@[]            =  (xs, xs)
307 span p xs@(x:xs')
308          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
309          | otherwise    =  ([],xs)
310
311 #ifdef USE_REPORT_PRELUDE
312 break p                 =  span (not . p)
313 #else
314 -- HBC version (stolen)
315 break _ xs@[]           =  (xs, xs)
316 break p xs@(x:xs')
317            | p x        =  ([],xs)
318            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
319 #endif
320
321 -- reverse xs returns the elements of xs in reverse order.  xs must be finite.
322 reverse                 :: [a] -> [a]
323 #ifdef USE_REPORT_PRELUDE
324 reverse                 =  foldl (flip (:)) []
325 #else
326 reverse l =  rev l []
327   where
328     rev []     a = a
329     rev (x:xs) a = rev xs (x:a)
330 #endif
331
332 -- and returns the conjunction of a Boolean list.  For the result to be
333 -- True, the list must be finite; False, however, results from a False
334 -- value at a finite index of a finite or infinite list.  or is the
335 -- disjunctive dual of and.
336 and, or                 :: [Bool] -> Bool
337 #ifdef USE_REPORT_PRELUDE
338 and                     =  foldr (&&) True
339 or                      =  foldr (||) False
340 #else
341 and []          =  True
342 and (x:xs)      =  x && and xs
343 or []           =  False
344 or (x:xs)       =  x || or xs
345
346 {-# RULES
347 "and/build"     forall g::forall b.(Bool->b->b)->b->b . 
348                 and (build g) = g (&&) True
349 "or/build"      forall g::forall b.(Bool->b->b)->b->b . 
350                 or (build g) = g (||) False
351  #-}
352 #endif
353
354 -- Applied to a predicate and a list, any determines if any element
355 -- of the list satisfies the predicate.  Similarly, for all.
356 any, all                :: (a -> Bool) -> [a] -> Bool
357 #ifdef USE_REPORT_PRELUDE
358 any p                   =  or . map p
359 all p                   =  and . map p
360 #else
361 any _ []        = False
362 any p (x:xs)    = p x || any p xs
363
364 all _ []        =  True
365 all p (x:xs)    =  p x && all p xs
366 {-# RULES
367 "any/build"     forall p, g::forall b.(a->b->b)->b->b . 
368                 any p (build g) = g ((||) . p) False
369 "all/build"     forall p, g::forall b.(a->b->b)->b->b . 
370                 all p (build g) = g ((&&) . p) True
371  #-}
372 #endif
373
374 -- elem is the list membership predicate, usually written in infix form,
375 -- e.g., x `elem` xs.  notElem is the negation.
376 elem, notElem           :: (Eq a) => a -> [a] -> Bool
377 #ifdef USE_REPORT_PRELUDE
378 elem x                  =  any (== x)
379 notElem x               =  all (/= x)
380 #else
381 elem _ []       = False
382 elem x (y:ys)   = x==y || elem x ys
383
384 notElem _ []    =  True
385 notElem x (y:ys)=  x /= y && notElem x ys
386 #endif
387
388 -- lookup key assocs looks up a key in an association list.
389 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
390 lookup _key []          =  Nothing
391 lookup  key ((x,y):xys)
392     | key == x          =  Just y
393     | otherwise         =  lookup key xys
394
395
396 -- maximum and minimum return the maximum or minimum value from a list,
397 -- which must be non-empty, finite, and of an ordered type.
398 {-# SPECIALISE maximum :: [Int] -> Int #-}
399 {-# SPECIALISE minimum :: [Int] -> Int #-}
400 maximum, minimum        :: (Ord a) => [a] -> a
401 maximum []              =  errorEmptyList "maximum"
402 maximum xs              =  foldl1 max xs
403
404 minimum []              =  errorEmptyList "minimum"
405 minimum xs              =  foldl1 min xs
406
407 concatMap               :: (a -> [b]) -> [a] -> [b]
408 concatMap f             =  foldr ((++) . f) []
409
410 concat :: [[a]] -> [a]
411 {-# INLINE concat #-}
412 concat = foldr (++) []
413 \end{code}
414
415
416 \begin{code}
417 -- List index (subscript) operator, 0-origin
418 (!!)                    :: [a] -> Int -> a
419 #ifdef USE_REPORT_PRELUDE
420 (x:_)  !! 0             =  x
421 (_:xs) !! n | n > 0     =  xs !! (n-1)
422 (_:_)  !! _             =  error "Prelude.(!!): negative index"
423 []     !! _             =  error "Prelude.(!!): index too large"
424 #else
425 -- HBC version (stolen), then unboxified
426 -- The semantics is not quite the same for error conditions
427 -- in the more efficient version.
428 --
429 xs !! (I# n) | n <# 0#   =  error "Prelude.(!!): negative index\n"
430              | otherwise =  sub xs n
431                          where
432                             sub :: [a] -> Int# -> a
433                             sub []     _ = error "Prelude.(!!): index too large\n"
434                             sub (y:ys) n = if n ==# 0#
435                                            then y
436                                            else sub ys (n -# 1#)
437 #endif
438 \end{code}
439
440
441 %*********************************************************
442 %*                                                      *
443 \subsection{The zip family}
444 %*                                                      *
445 %*********************************************************
446
447 \begin{code}
448 foldr2 k z []     ys     = z
449 foldr2 k z xs     []     = z
450 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
451
452 foldr2_left k z x r []     = z
453 foldr2_left k z x r (y:ys) = k x y (r ys)
454
455 foldr2_right k z y r []     = z
456 foldr2_right k z y r (x:xs) = k x y (r xs)
457
458 -- foldr2 k z xs ys = foldr (foldr2_left k z)  (\_ -> z) xs ys
459 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
460 {-# RULES
461 "foldr2/left"   forall k,z,ys,g::forall b.(a->b->b)->b->b . 
462                   foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys
463
464 "foldr2/right"  forall k,z,xs,g::forall b.(a->b->b)->b->b . 
465                   foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
466  #-}
467 \end{code}
468
469 zip takes two lists and returns a list of corresponding pairs.  If one
470 input list is short, excess elements of the longer list are discarded.
471 zip3 takes three lists and returns a list of triples.  Zips for larger
472 tuples are in the List library
473
474 \begin{code}
475 ----------------------------------------------
476 zip :: [a] -> [b] -> [(a,b)]
477 {-# INLINE zip #-}
478 zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
479
480 zipFB c x y r = (x,y) `c` r
481
482
483 zipList               :: [a] -> [b] -> [(a,b)]
484 zipList (a:as) (b:bs) = (a,b) : zipList as bs
485 zipList _      _      = []
486
487 {-# RULES
488 "zipList"       foldr2 (zipFB (:)) [] = zipList
489  #-}
490 \end{code}
491
492 \begin{code}
493 ----------------------------------------------
494 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
495 -- Specification
496 -- zip3 =  zipWith3 (,,)
497 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
498 zip3 _      _      _      = []
499 \end{code}
500
501
502 -- The zipWith family generalises the zip family by zipping with the
503 -- function given as the first argument, instead of a tupling function.
504 -- For example, zipWith (+) is applied to two lists to produce the list
505 -- of corresponding sums.
506
507
508 \begin{code}
509 ----------------------------------------------
510 zipWith :: (a->b->c) -> [a]->[b]->[c]
511 {-# INLINE zipWith #-}
512 zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
513
514 zipWithFB c f x y r = (x `f` y) `c` r
515
516 zipWithList                 :: (a->b->c) -> [a] -> [b] -> [c]
517 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
518 zipWithList f _      _      = []
519
520 {-# RULES
521 "zipWithList"   forall f. foldr2 (zipWithFB (:) f) [] = zipWithList f
522   #-}
523 \end{code}
524
525 \begin{code}
526 zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]
527 zipWith3 z (a:as) (b:bs) (c:cs)
528                         =  z a b c : zipWith3 z as bs cs
529 zipWith3 _ _ _ _        =  []
530
531 -- unzip transforms a list of pairs into a pair of lists.  
532 unzip    :: [(a,b)] -> ([a],[b])
533 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
534
535 unzip3   :: [(a,b,c)] -> ([a],[b],[c])
536 unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
537                   ([],[],[])
538 \end{code}
539
540
541 %*********************************************************
542 %*                                                      *
543 \subsection{Error code}
544 %*                                                      *
545 %*********************************************************
546
547 Common up near identical calls to `error' to reduce the number
548 constant strings created when compiled:
549
550 \begin{code}
551 errorEmptyList :: String -> a
552 errorEmptyList fun =
553   error (prel_list_str ++ fun ++ ": empty list")
554
555 errorNegativeIdx :: String -> a
556 errorNegativeIdx fun =
557  error (prel_list_str ++ fun ++ ": negative index")
558
559 prel_list_str :: String
560 prel_list_str = "Prelude."
561 \end{code}