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