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