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