99c1b5b3c4536d75ef2163502dbe25922e2fdc3c
[ghc-base.git] / GHC / List.lhs
1 \begin{code}
2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.List
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- The List data type and its operations
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.List (
18    -- [] (..),          -- Not Haskell 98; built in syntax
19
20    map, (++), filter, concat,
21    head, last, tail, init, null, length, (!!), 
22    foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
23    iterate, repeat, replicate, cycle,
24    take, drop, splitAt, takeWhile, dropWhile, span, break,
25    reverse, and, or,
26    any, all, elem, notElem, lookup,
27    maximum, minimum, concatMap,
28    zip, zip3, zipWith, zipWith3, unzip, unzip3,
29 #ifdef USE_REPORT_PRELUDE
30
31 #else
32
33    -- non-standard, but hidden when creating the Prelude
34    -- export list.
35    takeUInt_append
36
37 #endif
38
39  ) where
40
41 import {-# SOURCE #-} GHC.Err ( error )
42 import Data.Tuple
43 import Data.Maybe
44 import GHC.Base
45
46 infixl 9  !!
47 infix  4 `elem`, `notElem`
48 \end{code}
49
50 %*********************************************************
51 %*                                                      *
52 \subsection{List-manipulation functions}
53 %*                                                      *
54 %*********************************************************
55
56 \begin{code}
57 -- head and tail extract the first element and remaining elements,
58 -- respectively, of a list, which must be non-empty.  last and init
59 -- are the dual functions working from the end of a finite list,
60 -- rather than the beginning.
61
62 head                    :: [a] -> a
63 head (x:_)              =  x
64 head []                 =  badHead
65
66 badHead = errorEmptyList "head"
67
68 -- This rule is useful in cases like 
69 --      head [y | (x,y) <- ps, x==t]
70 {-# RULES
71 "head/build"    forall (g::forall b.(Bool->b->b)->b->b) . 
72                 head (build g) = g (\x _ -> x) badHead
73 "head/augment"  forall xs (g::forall b. (a->b->b) -> b -> b) . 
74                 head (augment g xs) = g (\x _ -> x) (head xs)
75  #-}
76
77 tail                    :: [a] -> [a]
78 tail (_:xs)             =  xs
79 tail []                 =  errorEmptyList "tail"
80
81 last                    :: [a] -> a
82 #ifdef USE_REPORT_PRELUDE
83 last [x]                =  x
84 last (_:xs)             =  last xs
85 last []                 =  errorEmptyList "last"
86 #else
87 -- eliminate repeated cases
88 last []                 =  errorEmptyList "last"
89 last (x:xs)             =  last' x xs
90   where last' y []     = y
91         last' _ (y:ys) = last' y ys
92 #endif
93
94 init                    :: [a] -> [a]
95 #ifdef USE_REPORT_PRELUDE
96 init [x]                =  []
97 init (x:xs)             =  x : init xs
98 init []                 =  errorEmptyList "init"
99 #else
100 -- eliminate repeated cases
101 init []                 =  errorEmptyList "init"
102 init (x:xs)             =  init' x xs
103   where init' _ []     = []
104         init' y (z:zs) = y : init' z zs
105 #endif
106
107 null                    :: [a] -> Bool
108 null []                 =  True
109 null (_:_)              =  False
110
111 -- length returns the length of a finite list as an Int; it is an instance
112 -- of the more general genericLength, the result type of which may be
113 -- any kind of number.
114 length                  :: [a] -> Int
115 length l                =  len l 0#
116   where
117     len :: [a] -> Int# -> Int
118     len []     a# = I# a#
119     len (_:xs) a# = len xs (a# +# 1#)
120
121 -- filter, applied to a predicate and a list, returns the list of those
122 -- elements that satisfy the predicate; i.e.,
123 -- filter p xs = [ x | x <- xs, p x]
124 filter :: (a -> Bool) -> [a] -> [a]
125 filter _pred []    = []
126 filter pred (x:xs)
127   | pred x         = x : filter pred xs
128   | otherwise      = filter pred xs
129
130 {-# NOINLINE [0] filterFB #-}
131 filterFB c p x r | p x       = x `c` r
132                  | otherwise = r
133
134 {-# RULES
135 "filter"     [~1] forall p xs.  filter p xs = build (\c n -> foldr (filterFB c p) n xs)
136 "filterList" [1]  forall p.     foldr (filterFB (:) p) [] = filter p
137 "filterFB"        forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
138  #-}
139
140 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
141 --     filterFB (filterFB c p) q a b
142 --   = if q a then filterFB c p a b else b
143 --   = if q a then (if p a then c a b else b) else b
144 --   = if q a && p a then c a b else b
145 --   = filterFB c (\x -> q x && p x) a b
146 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
147 -- gave rise to a live bug report.  SLPJ.
148
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 iterate f x =  x : iterate f (f x)
208
209 iterateFB c f x = x `c` iterateFB c f (f x)
210
211
212 {-# RULES
213 "iterate"    [~1] forall f x.   iterate f x = build (\c _n -> iterateFB c f x)
214 "iterateFB"  [1]                iterateFB (:) = iterate
215  #-}
216
217
218 -- repeat x is an infinite list, with x the value of every element.
219 repeat :: a -> [a]
220 {-# INLINE [0] repeat #-}
221 -- The pragma just gives the rules more chance to fire
222 repeat x = xs where xs = x : xs
223
224 {-# INLINE [0] repeatFB #-}     -- ditto
225 repeatFB c x = xs where xs = x `c` xs
226
227
228 {-# RULES
229 "repeat"    [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
230 "repeatFB"  [1]  repeatFB (:)       = repeat
231  #-}
232
233 -- replicate n x is a list of length n with x the value of every element
234 replicate               :: Int -> a -> [a]
235 replicate n x           =  take n (repeat x)
236
237 -- cycle ties a finite list into a circular one, or equivalently,
238 -- the infinite repetition of the original list.  It is the identity
239 -- on infinite lists.
240
241 cycle                   :: [a] -> [a]
242 cycle []                = error "Prelude.cycle: empty list"
243 cycle xs                = xs' where xs' = xs ++ xs'
244
245 -- takeWhile, applied to a predicate p and a list xs, returns the longest
246 -- prefix (possibly empty) of xs of elements that satisfy p.  dropWhile p xs
247 -- returns the remaining suffix.  Span p xs is equivalent to 
248 -- (takeWhile p xs, dropWhile p xs), while break p uses the negation of p.
249
250 takeWhile               :: (a -> Bool) -> [a] -> [a]
251 takeWhile _ []          =  []
252 takeWhile p (x:xs) 
253             | p x       =  x : takeWhile p xs
254             | otherwise =  []
255
256 dropWhile               :: (a -> Bool) -> [a] -> [a]
257 dropWhile _ []          =  []
258 dropWhile p xs@(x:xs')
259             | p x       =  dropWhile p xs'
260             | otherwise =  xs
261
262 -- take n, applied to a list xs, returns the prefix of xs of length n,
263 -- or xs itself if n > length xs.  drop n xs returns the suffix of xs
264 -- after the first n elements, or [] if n > length xs.  splitAt n xs
265 -- is equivalent to (take n xs, drop n xs).
266 #ifdef USE_REPORT_PRELUDE
267 take                   :: Int -> [a] -> [a]
268 take n _      | n <= 0 =  []
269 take _ []              =  []
270 take n (x:xs)          =  x : take (n-1) xs
271
272 drop                   :: Int -> [a] -> [a]
273 drop n xs     | n <= 0 =  xs
274 drop _ []              =  []
275 drop n (_:xs)          =  drop (n-1) xs
276
277 splitAt                  :: Int -> [a] -> ([a],[a])
278 splitAt n xs             =  (take n xs, drop n xs)
279
280 #else /* hack away */
281 take    :: Int -> [b] -> [b]
282 take (I# n#) xs = takeUInt n# xs
283
284 -- The general code for take, below, checks n <= maxInt
285 -- No need to check for maxInt overflow when specialised
286 -- at type Int or Int# since the Int must be <= maxInt
287
288 takeUInt :: Int# -> [b] -> [b]
289 takeUInt n xs
290   | n >=# 0#  =  take_unsafe_UInt n xs
291   | otherwise =  []
292
293 take_unsafe_UInt :: Int# -> [b] -> [b]
294 take_unsafe_UInt 0#  _  = []
295 take_unsafe_UInt m   ls =
296   case ls of
297     []     -> []
298     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
299
300 takeUInt_append :: Int# -> [b] -> [b] -> [b]
301 takeUInt_append n xs rs
302   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
303   | otherwise =  []
304
305 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
306 take_unsafe_UInt_append 0#  _ rs  = rs
307 take_unsafe_UInt_append m  ls rs  =
308   case ls of
309     []     -> rs
310     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
311
312 drop            :: Int -> [b] -> [b]
313 drop (I# n#) ls
314   | n# <# 0#    = []
315   | otherwise   = drop# n# ls
316     where
317         drop# :: Int# -> [a] -> [a]
318         drop# 0# xs      = xs
319         drop# _  xs@[]   = xs
320         drop# m# (_:xs)  = drop# (m# -# 1#) xs
321
322 splitAt :: Int -> [b] -> ([b], [b])
323 splitAt (I# n#) ls
324   | n# <# 0#    = ([], ls)
325   | otherwise   = splitAt# n# ls
326     where
327         splitAt# :: Int# -> [a] -> ([a], [a])
328         splitAt# 0# xs     = ([], xs)
329         splitAt# _  xs@[]  = (xs, xs)
330         splitAt# m# (x:xs) = (x:xs', xs'')
331           where
332             (xs', xs'') = splitAt# (m# -# 1#) xs
333
334 #endif /* USE_REPORT_PRELUDE */
335
336 span, break             :: (a -> Bool) -> [a] -> ([a],[a])
337 span _ xs@[]            =  (xs, xs)
338 span p xs@(x:xs')
339          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
340          | otherwise    =  ([],xs)
341
342 #ifdef USE_REPORT_PRELUDE
343 break p                 =  span (not . p)
344 #else
345 -- HBC version (stolen)
346 break _ xs@[]           =  (xs, xs)
347 break p xs@(x:xs')
348            | p x        =  ([],xs)
349            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
350 #endif
351
352 -- reverse xs returns the elements of xs in reverse order.  xs must be finite.
353 reverse                 :: [a] -> [a]
354 #ifdef USE_REPORT_PRELUDE
355 reverse                 =  foldl (flip (:)) []
356 #else
357 reverse l =  rev l []
358   where
359     rev []     a = a
360     rev (x:xs) a = rev xs (x:a)
361 #endif
362
363 -- and returns the conjunction of a Boolean list.  For the result to be
364 -- True, the list must be finite; False, however, results from a False
365 -- value at a finite index of a finite or infinite list.  or is the
366 -- disjunctive dual of and.
367 and, or                 :: [Bool] -> Bool
368 #ifdef USE_REPORT_PRELUDE
369 and                     =  foldr (&&) True
370 or                      =  foldr (||) False
371 #else
372 and []          =  True
373 and (x:xs)      =  x && and xs
374 or []           =  False
375 or (x:xs)       =  x || or xs
376
377 {-# RULES
378 "and/build"     forall (g::forall b.(Bool->b->b)->b->b) . 
379                 and (build g) = g (&&) True
380 "or/build"      forall (g::forall b.(Bool->b->b)->b->b) . 
381                 or (build g) = g (||) False
382  #-}
383 #endif
384
385 -- Applied to a predicate and a list, any determines if any element
386 -- of the list satisfies the predicate.  Similarly, for all.
387 any, all                :: (a -> Bool) -> [a] -> Bool
388 #ifdef USE_REPORT_PRELUDE
389 any p                   =  or . map p
390 all p                   =  and . map p
391 #else
392 any _ []        = False
393 any p (x:xs)    = p x || any p xs
394
395 all _ []        =  True
396 all p (x:xs)    =  p x && all p xs
397 {-# RULES
398 "any/build"     forall p (g::forall b.(a->b->b)->b->b) . 
399                 any p (build g) = g ((||) . p) False
400 "all/build"     forall p (g::forall b.(a->b->b)->b->b) . 
401                 all p (build g) = g ((&&) . p) True
402  #-}
403 #endif
404
405 -- elem is the list membership predicate, usually written in infix form,
406 -- e.g., x `elem` xs.  notElem is the negation.
407 elem, notElem           :: (Eq a) => a -> [a] -> Bool
408 #ifdef USE_REPORT_PRELUDE
409 elem x                  =  any (== x)
410 notElem x               =  all (/= x)
411 #else
412 elem _ []       = False
413 elem x (y:ys)   = x==y || elem x ys
414
415 notElem _ []    =  True
416 notElem x (y:ys)=  x /= y && notElem x ys
417 #endif
418
419 -- lookup key assocs looks up a key in an association list.
420 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
421 lookup _key []          =  Nothing
422 lookup  key ((x,y):xys)
423     | key == x          =  Just y
424     | otherwise         =  lookup key xys
425
426
427 -- maximum and minimum return the maximum or minimum value from a list,
428 -- which must be non-empty, finite, and of an ordered type.
429 {-# SPECIALISE maximum :: [Int] -> Int #-}
430 {-# SPECIALISE minimum :: [Int] -> Int #-}
431 maximum, minimum        :: (Ord a) => [a] -> a
432 maximum []              =  errorEmptyList "maximum"
433 maximum xs              =  foldl1 max xs
434
435 minimum []              =  errorEmptyList "minimum"
436 minimum xs              =  foldl1 min xs
437
438 concatMap               :: (a -> [b]) -> [a] -> [b]
439 concatMap f             =  foldr ((++) . f) []
440
441 concat :: [[a]] -> [a]
442 concat = foldr (++) []
443
444 {-# RULES
445   "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
446 -- We don't bother to turn non-fusible applications of concat back into concat
447  #-}
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 zip (a:as) (b:bs) = (a,b) : zip as bs
524 zip _      _      = []
525
526 {-# INLINE [0] zipFB #-}
527 zipFB c x y r = (x,y) `c` r
528
529 {-# RULES
530 "zip"      [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
531 "zipList"  [1]  foldr2 (zipFB (:)) []   = zip
532  #-}
533 \end{code}
534
535 \begin{code}
536 ----------------------------------------------
537 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
538 -- Specification
539 -- zip3 =  zipWith3 (,,)
540 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
541 zip3 _      _      _      = []
542 \end{code}
543
544
545 -- The zipWith family generalises the zip family by zipping with the
546 -- function given as the first argument, instead of a tupling function.
547 -- For example, zipWith (+) is applied to two lists to produce the list
548 -- of corresponding sums.
549
550
551 \begin{code}
552 ----------------------------------------------
553 zipWith :: (a->b->c) -> [a]->[b]->[c]
554 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
555 zipWith _ _      _      = []
556
557 {-# INLINE [0] zipWithFB #-}
558 zipWithFB c f x y r = (x `f` y) `c` r
559
560 {-# RULES
561 "zipWith"       [~1] forall f xs ys.    zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
562 "zipWithList"   [1]  forall f.  foldr2 (zipWithFB (:) f) [] = zipWith f
563   #-}
564 \end{code}
565
566 \begin{code}
567 zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]
568 zipWith3 z (a:as) (b:bs) (c:cs)
569                         =  z a b c : zipWith3 z as bs cs
570 zipWith3 _ _ _ _        =  []
571
572 -- unzip transforms a list of pairs into a pair of lists.  
573 unzip    :: [(a,b)] -> ([a],[b])
574 {-# INLINE unzip #-}
575 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
576
577 unzip3   :: [(a,b,c)] -> ([a],[b],[c])
578 {-# INLINE unzip3 #-}
579 unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
580                   ([],[],[])
581 \end{code}
582
583
584 %*********************************************************
585 %*                                                      *
586 \subsection{Error code}
587 %*                                                      *
588 %*********************************************************
589
590 Common up near identical calls to `error' to reduce the number
591 constant strings created when compiled:
592
593 \begin{code}
594 errorEmptyList :: String -> a
595 errorEmptyList fun =
596   error (prel_list_str ++ fun ++ ": empty list")
597
598 prel_list_str :: String
599 prel_list_str = "Prelude."
600 \end{code}