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