fe6750280c0df805164884ab22c9d5d59d0e1622
[ghc-base.git] / GHC / List.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.List
7 -- Copyright   :  (c) The University of Glasgow 1994-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC Extensions)
13 --
14 -- The List data type and its operations
15 --
16 -----------------------------------------------------------------------------
17
18 -- #hide
19 module GHC.List (
20    -- [] (..),          -- Not Haskell 98; built in syntax
21
22    map, (++), filter, concat,
23    head, last, tail, init, null, length, (!!),
24    foldl, scanl, scanl1, foldr, foldr1, scanr, scanr1,
25    iterate, repeat, replicate, cycle,
26    take, drop, splitAt, takeWhile, dropWhile, span, break,
27    reverse, and, or,
28    any, all, elem, notElem, lookup,
29    concatMap,
30    zip, zip3, zipWith, zipWith3, unzip, unzip3,
31    errorEmptyList,
32
33 #ifndef USE_REPORT_PRELUDE
34    -- non-standard, but hidden when creating the Prelude
35    -- export list.
36    takeUInt_append
37 #endif
38
39  ) where
40
41 import Data.Maybe
42 import GHC.Base
43
44 infixl 9  !!
45 infix  4 `elem`, `notElem`
46 \end{code}
47
48 %*********************************************************
49 %*                                                      *
50 \subsection{List-manipulation functions}
51 %*                                                      *
52 %*********************************************************
53
54 \begin{code}
55 -- | Extract the first element of a list, which must be non-empty.
56 head                    :: [a] -> a
57 head (x:_)              =  x
58 head []                 =  badHead
59
60 badHead :: a
61 badHead = errorEmptyList "head"
62
63 -- This rule is useful in cases like 
64 --      head [y | (x,y) <- ps, x==t]
65 {-# RULES
66 "head/build"    forall (g::forall b.(a->b->b)->b->b) .
67                 head (build g) = g (\x _ -> x) badHead
68 "head/augment"  forall xs (g::forall b. (a->b->b) -> b -> b) . 
69                 head (augment g xs) = g (\x _ -> x) (head xs)
70  #-}
71
72 -- | Extract the elements after the head of a list, which must be non-empty.
73 tail                    :: [a] -> [a]
74 tail (_:xs)             =  xs
75 tail []                 =  errorEmptyList "tail"
76
77 -- | Extract the last element of a list, which must be finite and non-empty.
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 -- | Return all the elements of a list except the last one.
92 -- The list must be non-empty.
93 init                    :: [a] -> [a]
94 #ifdef USE_REPORT_PRELUDE
95 init [x]                =  []
96 init (x:xs)             =  x : init xs
97 init []                 =  errorEmptyList "init"
98 #else
99 -- eliminate repeated cases
100 init []                 =  errorEmptyList "init"
101 init (x:xs)             =  init' x xs
102   where init' _ []     = []
103         init' y (z:zs) = y : init' z zs
104 #endif
105
106 -- | Test whether a list is empty.
107 null                    :: [a] -> Bool
108 null []                 =  True
109 null (_:_)              =  False
110
111 -- | /O(n)/. 'length' returns the length of a finite list as an 'Int'.
112 -- It is an instance of the more general 'Data.List.genericLength',
113 -- the result type of which may be 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
122 -- those elements that satisfy the predicate; i.e.,
123 --
124 -- > filter p xs = [ x | x <- xs, p x]
125
126 filter :: (a -> Bool) -> [a] -> [a]
127 filter _pred []    = []
128 filter pred (x:xs)
129   | pred x         = x : filter pred xs
130   | otherwise      = filter pred xs
131
132 {-# NOINLINE [0] filterFB #-}
133 filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
134 filterFB c p x r | p x       = x `c` r
135                  | otherwise = r
136
137 {-# RULES
138 "filter"     [~1] forall p xs.  filter p xs = build (\c n -> foldr (filterFB c p) n xs)
139 "filterList" [1]  forall p.     foldr (filterFB (:) p) [] = filter p
140 "filterFB"        forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
141  #-}
142
143 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
144 --     filterFB (filterFB c p) q a b
145 --   = if q a then filterFB c p a b else b
146 --   = if q a then (if p a then c a b else b) else b
147 --   = if q a && p a then c a b else b
148 --   = filterFB c (\x -> q x && p x) a b
149 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
150 -- gave rise to a live bug report.  SLPJ.
151
152
153 -- | 'foldl', applied to a binary operator, a starting value (typically
154 -- the left-identity of the operator), and a list, reduces the list
155 -- using the binary operator, from left to right:
156 --
157 -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
158 --
159 -- The list must be finite.
160
161 -- We write foldl as a non-recursive thing, so that it
162 -- can be inlined, and then (often) strictness-analysed,
163 -- and hence the classic space leak on foldl (+) 0 xs
164
165 foldl        :: (a -> b -> a) -> a -> [b] -> a
166 foldl f z0 xs0 = lgo z0 xs0
167              where
168                 lgo z []     =  z
169                 lgo z (x:xs) = lgo (f z x) xs
170
171 -- | 'scanl' is similar to 'foldl', but returns a list of successive
172 -- reduced values from the left:
173 --
174 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
175 --
176 -- Note that
177 --
178 -- > last (scanl f z xs) == foldl f z xs.
179
180 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
181 scanl f q ls            =  q : (case ls of
182                                 []   -> []
183                                 x:xs -> scanl f (f q x) xs)
184
185 -- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
186 --
187 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
188
189 scanl1                  :: (a -> a -> a) -> [a] -> [a]
190 scanl1 f (x:xs)         =  scanl f x xs
191 scanl1 _ []             =  []
192
193 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
194 -- above functions.
195
196 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
197 -- and thus must be applied to non-empty lists.
198
199 foldr1                  :: (a -> a -> a) -> [a] -> a
200 foldr1 _ [x]            =  x
201 foldr1 f (x:xs)         =  f x (foldr1 f xs)
202 foldr1 _ []             =  errorEmptyList "foldr1"
203
204 -- | 'scanr' is the right-to-left dual of 'scanl'.
205 -- Note that
206 --
207 -- > head (scanr f z xs) == foldr f z xs.
208
209 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
210 scanr _ q0 []           =  [q0]
211 scanr f q0 (x:xs)       =  f x q : qs
212                            where qs@(q:_) = scanr f q0 xs 
213
214 -- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
215
216 scanr1                  :: (a -> a -> a) -> [a] -> [a]
217 scanr1 _ []             =  []
218 scanr1 _ [x]            =  [x]
219 scanr1 f (x:xs)         =  f x q : qs
220                            where qs@(q:_) = scanr1 f xs 
221
222 -- | 'iterate' @f x@ returns an infinite list of repeated applications
223 -- of @f@ to @x@:
224 --
225 -- > iterate f x == [x, f x, f (f x), ...]
226
227 iterate :: (a -> a) -> a -> [a]
228 iterate f x =  x : iterate f (f x)
229
230 iterateFB :: (a -> b -> b) -> (a -> a) -> a -> b
231 iterateFB c f x = x `c` iterateFB c f (f x)
232
233
234 {-# RULES
235 "iterate"    [~1] forall f x.   iterate f x = build (\c _n -> iterateFB c f x)
236 "iterateFB"  [1]                iterateFB (:) = iterate
237  #-}
238
239
240 -- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
241 repeat :: a -> [a]
242 {-# INLINE [0] repeat #-}
243 -- The pragma just gives the rules more chance to fire
244 repeat x = xs where xs = x : xs
245
246 {-# INLINE [0] repeatFB #-}     -- ditto
247 repeatFB :: (a -> b -> b) -> a -> b
248 repeatFB c x = xs where xs = x `c` xs
249
250
251 {-# RULES
252 "repeat"    [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
253 "repeatFB"  [1]  repeatFB (:)       = repeat
254  #-}
255
256 -- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
257 -- every element.
258 -- It is an instance of the more general 'Data.List.genericReplicate',
259 -- in which @n@ may be of any integral type.
260 {-# INLINE replicate #-}
261 replicate               :: Int -> a -> [a]
262 replicate n x           =  take n (repeat x)
263
264 -- | 'cycle' ties a finite list into a circular one, or equivalently,
265 -- the infinite repetition of the original list.  It is the identity
266 -- on infinite lists.
267
268 cycle                   :: [a] -> [a]
269 cycle []                = error "Prelude.cycle: empty list"
270 cycle xs                = xs' where xs' = xs ++ xs'
271
272 -- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
273 -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@:
274 --
275 -- > takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
276 -- > takeWhile (< 9) [1,2,3] == [1,2,3]
277 -- > takeWhile (< 0) [1,2,3] == []
278 --
279
280 takeWhile               :: (a -> Bool) -> [a] -> [a]
281 takeWhile _ []          =  []
282 takeWhile p (x:xs) 
283             | p x       =  x : takeWhile p xs
284             | otherwise =  []
285
286 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@:
287 --
288 -- > dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
289 -- > dropWhile (< 9) [1,2,3] == []
290 -- > dropWhile (< 0) [1,2,3] == [1,2,3]
291 --
292
293 dropWhile               :: (a -> Bool) -> [a] -> [a]
294 dropWhile _ []          =  []
295 dropWhile p xs@(x:xs')
296             | p x       =  dropWhile p xs'
297             | otherwise =  xs
298
299 -- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
300 -- of length @n@, or @xs@ itself if @n > 'length' xs@:
301 --
302 -- > take 5 "Hello World!" == "Hello"
303 -- > take 3 [1,2,3,4,5] == [1,2,3]
304 -- > take 3 [1,2] == [1,2]
305 -- > take 3 [] == []
306 -- > take (-1) [1,2] == []
307 -- > take 0 [1,2] == []
308 --
309 -- It is an instance of the more general 'Data.List.genericTake',
310 -- in which @n@ may be of any integral type.
311 take                   :: Int -> [a] -> [a]
312
313 -- | 'drop' @n xs@ returns the suffix of @xs@
314 -- after the first @n@ elements, or @[]@ if @n > 'length' xs@:
315 --
316 -- > drop 6 "Hello World!" == "World!"
317 -- > drop 3 [1,2,3,4,5] == [4,5]
318 -- > drop 3 [1,2] == []
319 -- > drop 3 [] == []
320 -- > drop (-1) [1,2] == [1,2]
321 -- > drop 0 [1,2] == [1,2]
322 --
323 -- It is an instance of the more general 'Data.List.genericDrop',
324 -- in which @n@ may be of any integral type.
325 drop                   :: Int -> [a] -> [a]
326
327 -- | 'splitAt' @n xs@ returns a tuple where first element is @xs@ prefix of
328 -- length @n@ and second element is the remainder of the list:
329 --
330 -- > splitAt 6 "Hello World!" == ("Hello ","World!")
331 -- > splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
332 -- > splitAt 1 [1,2,3] == ([1],[2,3])
333 -- > splitAt 3 [1,2,3] == ([1,2,3],[])
334 -- > splitAt 4 [1,2,3] == ([1,2,3],[])
335 -- > splitAt 0 [1,2,3] == ([],[1,2,3])
336 -- > splitAt (-1) [1,2,3] == ([],[1,2,3])
337 --
338 -- It is equivalent to @('take' n xs, 'drop' n xs)@.
339 -- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt',
340 -- in which @n@ may be of any integral type.
341 splitAt                :: Int -> [a] -> ([a],[a])
342
343 #ifdef USE_REPORT_PRELUDE
344 take n _      | n <= 0 =  []
345 take _ []              =  []
346 take n (x:xs)          =  x : take (n-1) xs
347
348 drop n xs     | n <= 0 =  xs
349 drop _ []              =  []
350 drop n (_:xs)          =  drop (n-1) xs
351
352 splitAt n xs           =  (take n xs, drop n xs)
353
354 #else /* hack away */
355 {-# RULES
356 "take"     [~1] forall n xs . take n xs = takeFoldr n xs 
357 "takeList"  [1] forall n xs . foldr (takeFB (:) []) (takeConst []) xs n = takeUInt n xs
358  #-}
359
360 {-# INLINE takeFoldr #-}
361 takeFoldr :: Int -> [a] -> [a]
362 takeFoldr (I# n#) xs
363   = build (\c nil -> if n# <=# 0# then nil else
364                      foldr (takeFB c nil) (takeConst nil) xs n#)
365
366 {-# NOINLINE [0] takeConst #-}
367 -- just a version of const that doesn't get inlined too early, so we
368 -- can spot it in rules.  Also we need a type sig due to the unboxed Int#.
369 takeConst :: a -> Int# -> a
370 takeConst x _ = x
371
372 {-# NOINLINE [0] takeFB #-}
373 takeFB :: (a -> b -> b) -> b -> a -> (Int# -> b) -> Int# -> b
374 takeFB c n x xs m | m <=# 1#  = x `c` n
375                   | otherwise = x `c` xs (m -# 1#)
376
377 {-# INLINE [0] take #-}
378 take (I# n#) xs = takeUInt n# xs
379
380 -- The general code for take, below, checks n <= maxInt
381 -- No need to check for maxInt overflow when specialised
382 -- at type Int or Int# since the Int must be <= maxInt
383
384 takeUInt :: Int# -> [b] -> [b]
385 takeUInt n xs
386   | n >=# 0#  =  take_unsafe_UInt n xs
387   | otherwise =  []
388
389 take_unsafe_UInt :: Int# -> [b] -> [b]
390 take_unsafe_UInt 0#  _  = []
391 take_unsafe_UInt m   ls =
392   case ls of
393     []     -> []
394     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
395
396 takeUInt_append :: Int# -> [b] -> [b] -> [b]
397 takeUInt_append n xs rs
398   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
399   | otherwise =  []
400
401 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
402 take_unsafe_UInt_append 0#  _ rs  = rs
403 take_unsafe_UInt_append m  ls rs  =
404   case ls of
405     []     -> rs
406     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
407
408 drop (I# n#) ls
409   | n# <# 0#    = ls
410   | otherwise   = drop# n# ls
411     where
412         drop# :: Int# -> [a] -> [a]
413         drop# 0# xs      = xs
414         drop# _  xs@[]   = xs
415         drop# m# (_:xs)  = drop# (m# -# 1#) xs
416
417 splitAt (I# n#) ls
418   | n# <# 0#    = ([], ls)
419   | otherwise   = splitAt# n# ls
420     where
421         splitAt# :: Int# -> [a] -> ([a], [a])
422         splitAt# 0# xs     = ([], xs)
423         splitAt# _  xs@[]  = (xs, xs)
424         splitAt# m# (x:xs) = (x:xs', xs'')
425           where
426             (xs', xs'') = splitAt# (m# -# 1#) xs
427
428 #endif /* USE_REPORT_PRELUDE */
429
430 -- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where
431 -- first element is longest prefix (possibly empty) of @xs@ of elements that
432 -- satisfy @p@ and second element is the remainder of the list:
433 -- 
434 -- > span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
435 -- > span (< 9) [1,2,3] == ([1,2,3],[])
436 -- > span (< 0) [1,2,3] == ([],[1,2,3])
437 -- 
438 -- 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
439
440 span                    :: (a -> Bool) -> [a] -> ([a],[a])
441 span _ xs@[]            =  (xs, xs)
442 span p xs@(x:xs')
443          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
444          | otherwise    =  ([],xs)
445
446 -- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where
447 -- first element is longest prefix (possibly empty) of @xs@ of elements that
448 -- /do not satisfy/ @p@ and second element is the remainder of the list:
449 -- 
450 -- > break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
451 -- > break (< 9) [1,2,3] == ([],[1,2,3])
452 -- > break (> 9) [1,2,3] == ([1,2,3],[])
453 --
454 -- 'break' @p@ is equivalent to @'span' ('not' . p)@.
455
456 break                   :: (a -> Bool) -> [a] -> ([a],[a])
457 #ifdef USE_REPORT_PRELUDE
458 break p                 =  span (not . p)
459 #else
460 -- HBC version (stolen)
461 break _ xs@[]           =  (xs, xs)
462 break p xs@(x:xs')
463            | p x        =  ([],xs)
464            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
465 #endif
466
467 -- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
468 -- @xs@ must be finite.
469 reverse                 :: [a] -> [a]
470 #ifdef USE_REPORT_PRELUDE
471 reverse                 =  foldl (flip (:)) []
472 #else
473 reverse l =  rev l []
474   where
475     rev []     a = a
476     rev (x:xs) a = rev xs (x:a)
477 #endif
478
479 -- | 'and' returns the conjunction of a Boolean list.  For the result to be
480 -- 'True', the list must be finite; 'False', however, results from a 'False'
481 -- value at a finite index of a finite or infinite list.
482 and                     :: [Bool] -> Bool
483
484 -- | 'or' returns the disjunction of a Boolean list.  For the result to be
485 -- 'False', the list must be finite; 'True', however, results from a 'True'
486 -- value at a finite index of a finite or infinite list.
487 or                      :: [Bool] -> Bool
488 #ifdef USE_REPORT_PRELUDE
489 and                     =  foldr (&&) True
490 or                      =  foldr (||) False
491 #else
492 and []          =  True
493 and (x:xs)      =  x && and xs
494 or []           =  False
495 or (x:xs)       =  x || or xs
496
497 {-# RULES
498 "and/build"     forall (g::forall b.(Bool->b->b)->b->b) . 
499                 and (build g) = g (&&) True
500 "or/build"      forall (g::forall b.(Bool->b->b)->b->b) . 
501                 or (build g) = g (||) False
502  #-}
503 #endif
504
505 -- | Applied to a predicate and a list, 'any' determines if any element
506 -- of the list satisfies the predicate.  For the result to be
507 -- 'False', the list must be finite; 'True', however, results from a 'True'
508 -- value for the predicate applied to an element at a finite index of a finite or infinite list.
509 any                     :: (a -> Bool) -> [a] -> Bool
510
511 -- | Applied to a predicate and a list, 'all' determines if all elements
512 -- of the list satisfy the predicate. For the result to be
513 -- 'True', the list must be finite; 'False', however, results from a 'False'
514 -- value for the predicate applied to an element at a finite index of a finite or infinite list.
515 all                     :: (a -> Bool) -> [a] -> Bool
516 #ifdef USE_REPORT_PRELUDE
517 any p                   =  or . map p
518 all p                   =  and . map p
519 #else
520 any _ []        = False
521 any p (x:xs)    = p x || any p xs
522
523 all _ []        =  True
524 all p (x:xs)    =  p x && all p xs
525 {-# RULES
526 "any/build"     forall p (g::forall b.(a->b->b)->b->b) . 
527                 any p (build g) = g ((||) . p) False
528 "all/build"     forall p (g::forall b.(a->b->b)->b->b) . 
529                 all p (build g) = g ((&&) . p) True
530  #-}
531 #endif
532
533 -- | 'elem' is the list membership predicate, usually written in infix form,
534 -- e.g., @x \`elem\` xs@.  For the result to be
535 -- 'False', the list must be finite; 'True', however, results from an element equal to @x@ found at a finite index of a finite or infinite list.
536 elem                    :: (Eq a) => a -> [a] -> Bool
537
538 -- | 'notElem' is the negation of 'elem'.
539 notElem                 :: (Eq a) => a -> [a] -> Bool
540 #ifdef USE_REPORT_PRELUDE
541 elem x                  =  any (== x)
542 notElem x               =  all (/= x)
543 #else
544 elem _ []       = False
545 elem x (y:ys)   = x==y || elem x ys
546
547 notElem _ []    =  True
548 notElem x (y:ys)=  x /= y && notElem x ys
549 #endif
550
551 -- | 'lookup' @key assocs@ looks up a key in an association list.
552 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
553 lookup _key []          =  Nothing
554 lookup  key ((x,y):xys)
555     | key == x          =  Just y
556     | otherwise         =  lookup key xys
557
558 -- | Map a function over a list and concatenate the results.
559 concatMap               :: (a -> [b]) -> [a] -> [b]
560 concatMap f             =  foldr ((++) . f) []
561
562 -- | Concatenate a list of lists.
563 concat :: [[a]] -> [a]
564 concat = foldr (++) []
565
566 {-# RULES
567   "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)
568 -- We don't bother to turn non-fusible applications of concat back into concat
569  #-}
570
571 \end{code}
572
573
574 \begin{code}
575 -- | List index (subscript) operator, starting from 0.
576 -- It is an instance of the more general 'Data.List.genericIndex',
577 -- which takes an index of any integral type.
578 (!!)                    :: [a] -> Int -> a
579 #ifdef USE_REPORT_PRELUDE
580 xs     !! n | n < 0 =  error "Prelude.!!: negative index"
581 []     !! _         =  error "Prelude.!!: index too large"
582 (x:_)  !! 0         =  x
583 (_:xs) !! n         =  xs !! (n-1)
584 #else
585 -- HBC version (stolen), then unboxified
586 -- The semantics is not quite the same for error conditions
587 -- in the more efficient version.
588 --
589 xs !! (I# n0) | n0 <# 0#   =  error "Prelude.(!!): negative index\n"
590                | otherwise =  sub xs n0
591                          where
592                             sub :: [a] -> Int# -> a
593                             sub []     _ = error "Prelude.(!!): index too large\n"
594                             sub (y:ys) n = if n ==# 0#
595                                            then y
596                                            else sub ys (n -# 1#)
597 #endif
598 \end{code}
599
600
601 %*********************************************************
602 %*                                                      *
603 \subsection{The zip family}
604 %*                                                      *
605 %*********************************************************
606
607 \begin{code}
608 foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c
609 foldr2 _k z []    _ys    = z
610 foldr2 _k z _xs   []     = z
611 foldr2 k z (x:xs) (y:ys) = k x y (foldr2 k z xs ys)
612
613 foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d
614 foldr2_left _k  z _x _r []     = z
615 foldr2_left  k _z  x  r (y:ys) = k x y (r ys)
616
617 foldr2_right :: (a -> b -> c -> d) -> d -> b -> ([a] -> c) -> [a] -> d
618 foldr2_right _k z  _y _r []     = z
619 foldr2_right  k _z  y  r (x:xs) = k x y (r xs)
620
621 -- foldr2 k z xs ys = foldr (foldr2_left k z)  (\_ -> z) xs ys
622 -- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
623 {-# RULES
624 "foldr2/left"   forall k z ys (g::forall b.(a->b->b)->b->b) . 
625                   foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys
626
627 "foldr2/right"  forall k z xs (g::forall b.(a->b->b)->b->b) . 
628                   foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
629  #-}
630 \end{code}
631
632 The foldr2/right rule isn't exactly right, because it changes
633 the strictness of foldr2 (and thereby zip)
634
635 E.g. main = print (null (zip nonobviousNil (build undefined)))
636           where   nonobviousNil = f 3
637                   f n = if n == 0 then [] else f (n-1)
638
639 I'm going to leave it though.
640
641
642 Zips for larger tuples are in the List module.
643
644 \begin{code}
645 ----------------------------------------------
646 -- | 'zip' takes two lists and returns a list of corresponding pairs.
647 -- If one input list is short, excess elements of the longer list are
648 -- discarded.
649 zip :: [a] -> [b] -> [(a,b)]
650 zip (a:as) (b:bs) = (a,b) : zip as bs
651 zip _      _      = []
652
653 {-# INLINE [0] zipFB #-}
654 zipFB :: ((a, b) -> c -> d) -> a -> b -> c -> d
655 zipFB c = \x y r -> (x,y) `c` r
656
657 {-# RULES
658 "zip"      [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
659 "zipList"  [1]  foldr2 (zipFB (:)) []   = zip
660  #-}
661 \end{code}
662
663 \begin{code}
664 ----------------------------------------------
665 -- | 'zip3' takes three lists and returns a list of triples, analogous to
666 -- 'zip'.
667 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
668 -- Specification
669 -- zip3 =  zipWith3 (,,)
670 zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
671 zip3 _      _      _      = []
672 \end{code}
673
674
675 -- The zipWith family generalises the zip family by zipping with the
676 -- function given as the first argument, instead of a tupling function.
677
678 \begin{code}
679 ----------------------------------------------
680 -- | 'zipWith' generalises 'zip' by zipping with the function given
681 -- as the first argument, instead of a tupling function.
682 -- For example, @'zipWith' (+)@ is applied to two lists to produce the
683 -- list of corresponding sums.
684 zipWith :: (a->b->c) -> [a]->[b]->[c]
685 zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
686 zipWith _ _      _      = []
687
688 -- zipWithFB must have arity 2 since it gets two arguments in the "zipWith"
689 -- rule; it might not get inlined otherwise
690 {-# INLINE [0] zipWithFB #-}
691 zipWithFB :: (a -> b -> c) -> (d -> e -> a) -> d -> e -> b -> c
692 zipWithFB c f = \x y r -> (x `f` y) `c` r
693
694 {-# RULES
695 "zipWith"       [~1] forall f xs ys.    zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
696 "zipWithList"   [1]  forall f.  foldr2 (zipWithFB (:) f) [] = zipWith f
697   #-}
698 \end{code}
699
700 \begin{code}
701 -- | The 'zipWith3' function takes a function which combines three
702 -- elements, as well as three lists and returns a list of their point-wise
703 -- combination, analogous to 'zipWith'.
704 zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]
705 zipWith3 z (a:as) (b:bs) (c:cs)
706                         =  z a b c : zipWith3 z as bs cs
707 zipWith3 _ _ _ _        =  []
708
709 -- | 'unzip' transforms a list of pairs into a list of first components
710 -- and a list of second components.
711 unzip    :: [(a,b)] -> ([a],[b])
712 {-# INLINE unzip #-}
713 unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
714
715 -- | The 'unzip3' function takes a list of triples and returns three
716 -- lists, analogous to 'unzip'.
717 unzip3   :: [(a,b,c)] -> ([a],[b],[c])
718 {-# INLINE unzip3 #-}
719 unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
720                   ([],[],[])
721 \end{code}
722
723
724 %*********************************************************
725 %*                                                      *
726 \subsection{Error code}
727 %*                                                      *
728 %*********************************************************
729
730 Common up near identical calls to `error' to reduce the number
731 constant strings created when compiled:
732
733 \begin{code}
734 errorEmptyList :: String -> a
735 errorEmptyList fun =
736   error (prel_list_str ++ fun ++ ": empty list")
737
738 prel_list_str :: String
739 prel_list_str = "Prelude."
740 \end{code}