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