496aa1ea1215f1baabb17886e588fd3cdb4ab6ab
[ghc-hetmet.git] / ghc / lib / std / PrelList.lhs
1 % ------------------------------------------------------------------------------
2 % $Id: PrelList.lhs,v 1.21 2000/08/29 16:35:56 simonpj 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 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
134 --     filterFB (filterFB c p) q a b
135 --   = if q a then filterFB c p a b else b
136 --   = if q a then (if p a then c a b else b) else b
137 --   = if q a && p a then c a b else b
138 --   = filterFB c (\x -> q x && p x) a b
139 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
140 -- gave rise to a live bug report.  SLPJ.
141
142 filterList :: (a -> Bool) -> [a] -> [a]
143 filterList _pred []    = []
144 filterList pred (x:xs)
145   | pred x         = x : filterList pred xs
146   | otherwise      = filterList pred xs
147
148 -- foldl, applied to a binary operator, a starting value (typically the
149 -- left-identity of the operator), and a list, reduces the list using
150 -- the binary operator, from left to right:
151 --  foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
152 -- foldl1 is a variant that has no starting value argument, and  thus must
153 -- be applied to non-empty lists.  scanl is similar to foldl, but returns
154 -- a list of successive reduced values from the left:
155 --      scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
156 -- Note that  last (scanl f z xs) == foldl f z xs.
157 -- scanl1 is similar, again without the starting element:
158 --      scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
159
160 foldl                   :: (a -> b -> a) -> a -> [b] -> a
161 foldl _ z []            =  z
162 foldl f z (x:xs)        =  foldl f (f z x) xs
163
164 foldl1                  :: (a -> a -> a) -> [a] -> a
165 foldl1 f (x:xs)         =  foldl f x xs
166 foldl1 _ []             =  errorEmptyList "foldl1"
167
168 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
169 scanl f q ls            =  q : (case ls of
170                                 []   -> []
171                                 x:xs -> scanl f (f q x) xs)
172
173 scanl1                  :: (a -> a -> a) -> [a] -> [a]
174 scanl1 f (x:xs)         =  scanl f x xs
175 scanl1 _ []             =  errorEmptyList "scanl1"
176
177 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
178 -- above functions.
179
180 foldr1                  :: (a -> a -> a) -> [a] -> a
181 foldr1 _ [x]            =  x
182 foldr1 f (x:xs)         =  f x (foldr1 f xs)
183 foldr1 _ []             =  errorEmptyList "foldr1"
184
185 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
186 scanr _ q0 []           =  [q0]
187 scanr f q0 (x:xs)       =  f x q : qs
188                            where qs@(q:_) = scanr f q0 xs 
189
190 scanr1                  :: (a -> a -> a) -> [a] -> [a]
191 scanr1 _  [x]           =  [x]
192 scanr1 f  (x:xs)        =  f x q : qs
193                            where qs@(q:_) = scanr1 f xs 
194 scanr1 _ []             =  errorEmptyList "scanr1"
195
196 -- iterate f x returns an infinite list of repeated applications of f to x:
197 -- iterate f x == [x, f x, f (f x), ...]
198 iterate :: (a -> a) -> a -> [a]
199 iterate = iterateList
200
201 iterateFB c f x = x `c` iterateFB c f (f x)
202
203 iterateList f x =  x : iterateList f (f x)
204
205 {-# RULES
206 "iterate"       forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
207 "iterateFB"                     iterateFB (:) = iterateList
208  #-}
209
210
211 -- repeat x is an infinite list, with x the value of every element.
212 repeat :: a -> [a]
213 repeat = repeatList
214
215 repeatFB c x = xs where xs = x `c` xs
216 repeatList x = xs where xs = x :   xs
217
218 {-# RULES
219 "repeat"        forall x. repeat x      = build (\c _n -> repeatFB c x)
220 "repeatFB"                repeatFB (:)  = repeatList
221  #-}
222
223 -- replicate n x is a list of length n with x the value of every element
224 replicate               :: Int -> a -> [a]
225 replicate n x           =  take n (repeat x)
226
227 -- cycle ties a finite list into a circular one, or equivalently,
228 -- the infinite repetition of the original list.  It is the identity
229 -- on infinite lists.
230
231 cycle                   :: [a] -> [a]
232 cycle []                = error "Prelude.cycle: empty list"
233 cycle xs                = xs' where xs' = xs ++ xs'
234
235 -- takeWhile, applied to a predicate p and a list xs, returns the longest
236 -- prefix (possibly empty) of xs of elements that satisfy p.  dropWhile p xs
237 -- returns the remaining suffix.  Span p xs is equivalent to 
238 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
239
240 takeWhile               :: (a -> Bool) -> [a] -> [a]
241 takeWhile _ []          =  []
242 takeWhile p (x:xs) 
243             | p x       =  x : takeWhile p xs
244             | otherwise =  []
245
246 dropWhile               :: (a -> Bool) -> [a] -> [a]
247 dropWhile _ []          =  []
248 dropWhile p xs@(x:xs')
249             | p x       =  dropWhile p xs'
250             | otherwise =  xs
251
252 -- take n, applied to a list xs, returns the prefix of xs of length n,
253 -- or xs itself if n > length xs.  drop n xs returns the suffix of xs
254 -- after the first n elements, or [] if n > length xs.  splitAt n xs
255 -- is equivalent to (take n xs, drop n xs).
256 #ifdef USE_REPORT_PRELUDE
257 take                   :: Int -> [a] -> [a]
258 take 0 _               =  []
259 take _ []              =  []
260 take n (x:xs) | n > 0  =  x : take (minusInt n 1) xs
261 take _     _           =  errorNegativeIdx "take"
262
263 drop                   :: Int -> [a] -> [a]
264 drop 0 xs              =  xs
265 drop _ []              =  []
266 drop n (_:xs) | n > 0  =  drop (minusInt n 1) xs
267 drop _     _           =  errorNegativeIdx "drop"
268
269
270 splitAt                   :: Int -> [a] -> ([a],[a])
271 splitAt 0 xs              =  ([],xs)
272 splitAt _ []              =  ([],[])
273 splitAt n (x:xs) | n > 0  =  (x:xs',xs'') where (xs',xs'') = splitAt (minusInt n 1) xs
274 splitAt _     _           =  errorNegativeIdx "splitAt"
275
276 #else /* hack away */
277 take    :: Int -> [b] -> [b]
278 take (I# n#) xs = takeUInt n# xs
279
280 -- The general code for take, below, checks n <= maxInt
281 -- No need to check for maxInt overflow when specialised
282 -- at type Int or Int# since the Int must be <= maxInt
283
284 takeUInt :: Int# -> [b] -> [b]
285 takeUInt n xs
286   | n >=# 0#  =  take_unsafe_UInt n xs
287   | otherwise =  errorNegativeIdx "take"
288
289 take_unsafe_UInt :: Int# -> [b] -> [b]
290 take_unsafe_UInt 0#  _  = []
291 take_unsafe_UInt m   ls =
292   case ls of
293     []     -> []
294     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
295
296 takeUInt_append :: Int# -> [b] -> [b] -> [b]
297 takeUInt_append n xs rs
298   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
299   | otherwise =  errorNegativeIdx "take"
300
301 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
302 take_unsafe_UInt_append 0#  _ rs  = rs
303 take_unsafe_UInt_append m  ls rs  =
304   case ls of
305     []     -> rs
306     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
307
308 drop            :: Int -> [b] -> [b]
309 drop (I# n#) ls
310   | n# <# 0#    = errorNegativeIdx "drop"
311   | otherwise   = drop# n# ls
312     where
313         drop# :: Int# -> [a] -> [a]
314         drop# 0# xs      = xs
315         drop# _  xs@[]   = xs
316         drop# m# (_:xs)  = drop# (m# -# 1#) xs
317
318 splitAt :: Int -> [b] -> ([b], [b])
319 splitAt (I# n#) ls
320   | n# <# 0#    = errorNegativeIdx "splitAt"
321   | otherwise   = splitAt# n# ls
322     where
323         splitAt# :: Int# -> [a] -> ([a], [a])
324         splitAt# 0# xs     = ([], xs)
325         splitAt# _  xs@[]  = (xs, xs)
326         splitAt# m# (x:xs) = (x:xs', xs'')
327           where
328             (xs', xs'') = splitAt# (m# -# 1#) xs
329
330 #endif /* USE_REPORT_PRELUDE */
331
332 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
333 span _ xs@[]            =  (xs, xs)
334 span p xs@(x:xs')
335          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
336          | otherwise    =  ([],xs)
337
338 #ifdef USE_REPORT_PRELUDE
339 break p                 =  span (not . p)
340 #else
341 -- HBC version (stolen)
342 break _ xs@[]           =  (xs, xs)
343 break p xs@(x:xs')
344            | p x        =  ([],xs)
345            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
346 #endif
347
348 -- reverse xs returns the elements of xs in reverse order.  xs must be finite.
349 reverse                 :: [a] -> [a]
350 #ifdef USE_REPORT_PRELUDE
351 reverse                 =  foldl (flip (:)) []
352 #else
353 reverse l =  rev l []
354   where
355     rev []     a = a
356     rev (x:xs) a = rev xs (x:a)
357 #endif
358
359 -- and returns the conjunction of a Boolean list.  For the result to be
360 -- True, the list must be finite; False, however, results from a False
361 -- value at a finite index of a finite or infinite list.  or is the
362 -- disjunctive dual of and.
363 and, or                 :: [Bool] -> Bool
364 #ifdef USE_REPORT_PRELUDE
365 and                     =  foldr (&&) True
366 or                      =  foldr (||) False
367 #else
368 and []          =  True
369 and (x:xs)      =  x && and xs
370 or []           =  False
371 or (x:xs)       =  x || or xs
372
373 {-# RULES
374 "and/build"     forall (g::forall b.(Bool->b->b)->b->b) . 
375                 and (build g) = g (&&) True
376 "or/build"      forall (g::forall b.(Bool->b->b)->b->b) . 
377                 or (build g) = g (||) False
378  #-}
379 #endif
380
381 -- Applied to a predicate and a list, any determines if any element
382 -- of the list satisfies the predicate.  Similarly, for all.
383 any, all                :: (a -> Bool) -> [a] -> Bool
384 #ifdef USE_REPORT_PRELUDE
385 any p                   =  or . map p
386 all p                   =  and . map p
387 #else
388 any _ []        = False
389 any p (x:xs)    = p x || any p xs
390
391 all _ []        =  True
392 all p (x:xs)    =  p x && all p xs
393 {-# RULES
394 "any/build"     forall p (g::forall b.(a->b->b)->b->b) . 
395                 any p (build g) = g ((||) . p) False
396 "all/build"     forall p (g::forall b.(a->b->b)->b->b) . 
397                 all p (build g) = g ((&&) . p) True
398  #-}
399 #endif
400
401 -- elem is the list membership predicate, usually written in infix form,
402 -- e.g., x `elem` xs.  notElem is the negation.
403 elem, notElem           :: (Eq a) => a -> [a] -> Bool
404 #ifdef USE_REPORT_PRELUDE
405 elem x                  =  any (== x)
406 notElem x               =  all (/= x)
407 #else
408 elem _ []       = False
409 elem x (y:ys)   = x==y || elem x ys
410
411 notElem _ []    =  True
412 notElem x (y:ys)=  x /= y && notElem x ys
413 #endif
414
415 -- lookup key assocs looks up a key in an association list.
416 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
417 lookup _key []          =  Nothing
418 lookup  key ((x,y):xys)
419     | key == x          =  Just y
420     | otherwise         =  lookup key xys
421
422
423 -- maximum and minimum return the maximum or minimum value from a list,
424 -- which must be non-empty, finite, and of an ordered type.
425 {-# SPECIALISE maximum :: [Int] -> Int #-}
426 {-# SPECIALISE minimum :: [Int] -> Int #-}
427 maximum, minimum        :: (Ord a) => [a] -> a
428 maximum []              =  errorEmptyList "maximum"
429 maximum xs              =  foldl1 max xs
430
431 minimum []              =  errorEmptyList "minimum"
432 minimum xs              =  foldl1 min xs
433
434 concatMap               :: (a -> [b]) -> [a] -> [b]
435 concatMap f             =  foldr ((++) . f) []
436
437 concat :: [[a]] -> [a]
438 {-# INLINE concat #-}
439 concat = foldr (++) []
440 \end{code}
441
442
443 \begin{code}
444 -- List index (subscript) operator, 0-origin
445 (!!)                    :: [a] -> Int -> a
446 #ifdef USE_REPORT_PRELUDE
447 (x:_)  !! 0             =  x
448 (_:xs) !! n | n > 0     =  xs !! (minusInt n 1)
449 (_:_)  !! _             =  error "Prelude.(!!): negative index"
450 []     !! _             =  error "Prelude.(!!): index too large"
451 #else
452 -- HBC version (stolen), then unboxified
453 -- The semantics is not quite the same for error conditions
454 -- in the more efficient version.
455 --
456 xs !! (I# n) | n <# 0#   =  error "Prelude.(!!): negative index\n"
457              | otherwise =  sub xs n
458                          where
459                             sub :: [a] -> Int# -> a
460                             sub []     _ = error "Prelude.(!!): index too large\n"
461                             sub (y:ys) n = if n ==# 0#
462                                            then y
463                                            else sub ys (n -# 1#)
464 #endif
465 \end{code}
466
467
468 %*********************************************************
469 %*                                                      *
470 \subsection{The zip family}
471 %*                                                      *
472 %*********************************************************
473
474 \begin{code}
475 foldr2 _k z []    _ys    = z
476 foldr2 _k z _xs   []     = z
477 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
478
479 foldr2_left _k  z _x _r []     = z
480 foldr2_left  k _z  x  r (y:ys) = k x y (r ys)
481
482 foldr2_right _k z  _y _r []     = z
483 foldr2_right  k _z  y  r (x:xs) = k x y (r xs)
484
485 -- foldr2 k z xs ys = foldr (foldr2_left k z)  (\_ -> z) xs ys
486 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
487 {-# RULES
488 "foldr2/left"   forall k z ys (g::forall b.(a->b->b)->b->b) . 
489                   foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys
490
491 "foldr2/right"  forall k z xs (g::forall b.(a->b->b)->b->b) . 
492                   foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
493  #-}
494 \end{code}
495
496 The foldr2/right rule isn't exactly right, because it changes
497 the strictness of foldr2 (and thereby zip)
498
499 E.g. main = print (null (zip nonobviousNil (build undefined)))
500           where   nonobviousNil = f 3
501                   f n = if n == 0 then [] else f (n-1)
502
503 I'm going to leave it though.
504
505
506 zip takes two lists and returns a list of corresponding pairs.  If one
507 input list is short, excess elements of the longer list are discarded.
508 zip3 takes three lists and returns a list of triples.  Zips for larger
509 tuples are in the List library
510
511 \begin{code}
512 ----------------------------------------------
513 zip :: [a] -> [b] -> [(a,b)]
514 zip = zipList
515
516 zipFB c x y r = (x,y) `c` r
517
518
519 zipList               :: [a] -> [b] -> [(a,b)]
520 zipList (a:as) (b:bs) = (a,b) : zipList as bs
521 zipList _      _      = []
522
523 {-# RULES
524 "zip"           forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
525 "zipList"       foldr2 (zipFB (:)) []   = zipList
526  #-}
527 \end{code}
528
529 \begin{code}
530 ----------------------------------------------
531 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
532 -- Specification
533 -- zip3 =  zipWith3 (,,)
534 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
535 zip3 _      _      _      = []
536 \end{code}
537
538
539 -- The zipWith family generalises the zip family by zipping with the
540 -- function given as the first argument, instead of a tupling function.
541 -- For example, zipWith (+) is applied to two lists to produce the list
542 -- of corresponding sums.
543
544
545 \begin{code}
546 ----------------------------------------------
547 zipWith :: (a->b->c) -> [a]->[b]->[c]
548 zipWith = zipWithList
549
550
551 zipWithFB c f x y r = (x `f` y) `c` r
552
553 zipWithList                 :: (a->b->c) -> [a] -> [b] -> [c]
554 zipWithList f (a:as) (b:bs) = f a b : zipWithList f as bs
555 zipWithList _ _      _      = []
556
557 {-# RULES
558 "zipWith"       forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
559 "zipWithList"   forall f.       foldr2 (zipWithFB (:) f) [] = zipWithList f
560   #-}
561 \end{code}
562
563 \begin{code}
564 zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]
565 zipWith3 z (a:as) (b:bs) (c:cs)
566                         =  z a b c : zipWith3 z as bs cs
567 zipWith3 _ _ _ _        =  []
568
569 -- unzip transforms a list of pairs into a pair of lists.  
570 unzip    :: [(a,b)] -> ([a],[b])
571 {-# INLINE unzip #-}
572 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
573
574 unzip3   :: [(a,b,c)] -> ([a],[b],[c])
575 {-# INLINE unzip3 #-}
576 unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
577                   ([],[],[])
578 \end{code}
579
580
581 %*********************************************************
582 %*                                                      *
583 \subsection{Error code}
584 %*                                                      *
585 %*********************************************************
586
587 Common up near identical calls to `error' to reduce the number
588 constant strings created when compiled:
589
590 \begin{code}
591 errorEmptyList :: String -> a
592 errorEmptyList fun =
593   error (prel_list_str ++ fun ++ ": empty list")
594
595 errorNegativeIdx :: String -> a
596 errorNegativeIdx fun =
597  error (prel_list_str ++ fun ++ ": negative index")
598
599 prel_list_str :: String
600 prel_list_str = "Prelude."
601 \end{code}