disambiguate uses of foldr for nhc98 to compile without errors
[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 = lenAcc 0# l
116
117 {-# RULES
118 "length" [~1] forall xs. length xs = foldr incL (I# 0#) xs
119 "lenAcc" [1]  forall n#. foldr incL (I# n#) = lenAcc n#
120  #-}
121
122 incL :: a -> Int -> Int         -- Internal
123 {-# NOINLINE [0] incL #-}
124 incL x n = n `plusInt` oneInt
125
126 lenAcc :: Int# -> [a] -> Int    -- Internal
127 lenAcc a# []     = I# a#
128 lenAcc a# (_:xs) = lenAcc (a# +# 1#) xs
129
130 -- | 'filter', applied to a predicate and a list, returns the list of
131 -- those elements that satisfy the predicate; i.e.,
132 --
133 -- > filter p xs = [ x | x <- xs, p x]
134
135 filter :: (a -> Bool) -> [a] -> [a]
136 filter _pred []    = []
137 filter pred (x:xs)
138   | pred x         = x : filter pred xs
139   | otherwise      = filter pred xs
140
141 {-# NOINLINE [0] filterFB #-}
142 filterFB c p x r | p x       = x `c` r
143                  | otherwise = r
144
145 {-# RULES
146 "filter"     [~1] forall p xs.  filter p xs = build (\c n -> foldr (filterFB c p) n xs)
147 "filterList" [1]  forall p.     foldr (filterFB (:) p) [] = filter p
148 "filterFB"        forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
149  #-}
150
151 -- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
152 --     filterFB (filterFB c p) q a b
153 --   = if q a then filterFB c p a b else b
154 --   = if q a then (if p a then c a b else b) else b
155 --   = if q a && p a then c a b else b
156 --   = filterFB c (\x -> q x && p x) a b
157 -- I originally wrote (\x -> p x && q x), which is wrong, and actually
158 -- gave rise to a live bug report.  SLPJ.
159
160
161 -- | 'foldl', applied to a binary operator, a starting value (typically
162 -- the left-identity of the operator), and a list, reduces the list
163 -- using the binary operator, from left to right:
164 --
165 -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
166 --
167 -- The list must be finite.
168
169 -- We write foldl as a non-recursive thing, so that it
170 -- can be inlined, and then (often) strictness-analysed,
171 -- and hence the classic space leak on foldl (+) 0 xs
172
173 foldl        :: (a -> b -> a) -> a -> [b] -> a
174 foldl f z xs = lgo z xs
175              where
176                 lgo z []     =  z
177                 lgo z (x:xs) = lgo (f z x) xs
178
179 -- | 'scanl' is similar to 'foldl', but returns a list of successive
180 -- reduced values from the left:
181 --
182 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
183 --
184 -- Note that
185 --
186 -- > last (scanl f z xs) == foldl f z xs.
187
188 scanl                   :: (a -> b -> a) -> a -> [b] -> [a]
189 scanl f q ls            =  q : (case ls of
190                                 []   -> []
191                                 x:xs -> scanl f (f q x) xs)
192
193 -- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
194 --
195 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
196
197 scanl1                  :: (a -> a -> a) -> [a] -> [a]
198 scanl1 f (x:xs)         =  scanl f x xs
199 scanl1 _ []             =  []
200
201 -- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
202 -- above functions.
203
204 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
205 -- and thus must be applied to non-empty lists.
206
207 foldr1                  :: (a -> a -> a) -> [a] -> a
208 foldr1 _ [x]            =  x
209 foldr1 f (x:xs)         =  f x (foldr1 f xs)
210 foldr1 _ []             =  errorEmptyList "foldr1"
211
212 -- | 'scanr' is the right-to-left dual of 'scanl'.
213 -- Note that
214 --
215 -- > head (scanr f z xs) == foldr f z xs.
216
217 scanr                   :: (a -> b -> b) -> b -> [a] -> [b]
218 scanr _ q0 []           =  [q0]
219 scanr f q0 (x:xs)       =  f x q : qs
220                            where qs@(q:_) = scanr f q0 xs 
221
222 -- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
223
224 scanr1                  :: (a -> a -> a) -> [a] -> [a]
225 scanr1 f []             =  []
226 scanr1 f [x]            =  [x]
227 scanr1 f (x:xs)         =  f x q : qs
228                            where qs@(q:_) = scanr1 f xs 
229
230 -- | 'iterate' @f x@ returns an infinite list of repeated applications
231 -- of @f@ to @x@:
232 --
233 -- > iterate f x == [x, f x, f (f x), ...]
234
235 iterate :: (a -> a) -> a -> [a]
236 iterate f x =  x : iterate f (f x)
237
238 iterateFB c f x = x `c` iterateFB c f (f x)
239
240
241 {-# RULES
242 "iterate"    [~1] forall f x.   iterate f x = build (\c _n -> iterateFB c f x)
243 "iterateFB"  [1]                iterateFB (:) = iterate
244  #-}
245
246
247 -- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
248 repeat :: a -> [a]
249 {-# INLINE [0] repeat #-}
250 -- The pragma just gives the rules more chance to fire
251 repeat x = xs where xs = x : xs
252
253 {-# INLINE [0] repeatFB #-}     -- ditto
254 repeatFB c x = xs where xs = x `c` xs
255
256
257 {-# RULES
258 "repeat"    [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
259 "repeatFB"  [1]  repeatFB (:)       = repeat
260  #-}
261
262 -- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
263 -- every element.
264 -- It is an instance of the more general 'Data.List.genericReplicate',
265 -- in which @n@ may be of any integral type.
266 {-# INLINE replicate #-}
267 replicate               :: Int -> a -> [a]
268 replicate n x           =  take n (repeat x)
269
270 -- | 'cycle' ties a finite list into a circular one, or equivalently,
271 -- the infinite repetition of the original list.  It is the identity
272 -- on infinite lists.
273
274 cycle                   :: [a] -> [a]
275 cycle []                = error "Prelude.cycle: empty list"
276 cycle xs                = xs' where xs' = xs ++ xs'
277
278 -- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
279 -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@.
280
281 takeWhile               :: (a -> Bool) -> [a] -> [a]
282 takeWhile _ []          =  []
283 takeWhile p (x:xs) 
284             | p x       =  x : takeWhile p xs
285             | otherwise =  []
286
287 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
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 -- It is an instance of the more general 'Data.List.genericTake',
298 -- in which @n@ may be of any integral type.
299 take                   :: Int -> [a] -> [a]
300
301 -- | 'drop' @n xs@ returns the suffix of @xs@
302 -- after the first @n@ elements, or @[]@ if @n > 'length' xs@.
303 -- It is an instance of the more general 'Data.List.genericDrop',
304 -- in which @n@ may be of any integral type.
305 drop                   :: Int -> [a] -> [a]
306
307 -- | 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
308 -- It is an instance of the more general 'Data.List.genericSplitAt',
309 -- in which @n@ may be of any integral type.
310 splitAt                :: Int -> [a] -> ([a],[a])
311
312 #ifdef USE_REPORT_PRELUDE
313 take n _      | n <= 0 =  []
314 take _ []              =  []
315 take n (x:xs)          =  x : take (n-1) xs
316
317 drop n xs     | n <= 0 =  xs
318 drop _ []              =  []
319 drop n (_:xs)          =  drop (n-1) xs
320
321 splitAt n xs           =  (take n xs, drop n xs)
322
323 #else /* hack away */
324 {-# RULES
325 "take"     [~1] forall n xs . take n xs = case n of I# n# -> build (\c nil -> foldr (takeFB c nil) (takeConst nil) xs n#)
326 "takeList"  [1] forall n xs . foldr (takeFB (:) []) (takeConst []) xs n = takeUInt n xs
327  #-}
328
329 {-# NOINLINE [0] takeConst #-}
330 -- just a version of const that doesn't get inlined too early, so we
331 -- can spot it in rules.  Also we need a type sig due to the unboxed Int#.
332 takeConst :: a -> Int# -> a
333 takeConst x _ = x
334
335 {-# NOINLINE [0] takeFB #-}
336 takeFB :: (a -> b -> c) -> c -> a -> (Int# -> b) -> Int# -> c
337 takeFB c n x xs m | m <=# 0#  = n
338                   | otherwise = x `c` xs (m -# 1#)
339
340 {-# INLINE [0] take #-}
341 take (I# n#) xs = takeUInt n# xs
342
343 -- The general code for take, below, checks n <= maxInt
344 -- No need to check for maxInt overflow when specialised
345 -- at type Int or Int# since the Int must be <= maxInt
346
347 takeUInt :: Int# -> [b] -> [b]
348 takeUInt n xs
349   | n >=# 0#  =  take_unsafe_UInt n xs
350   | otherwise =  []
351
352 take_unsafe_UInt :: Int# -> [b] -> [b]
353 take_unsafe_UInt 0#  _  = []
354 take_unsafe_UInt m   ls =
355   case ls of
356     []     -> []
357     (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs
358
359 takeUInt_append :: Int# -> [b] -> [b] -> [b]
360 takeUInt_append n xs rs
361   | n >=# 0#  =  take_unsafe_UInt_append n xs rs
362   | otherwise =  []
363
364 take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b]
365 take_unsafe_UInt_append 0#  _ rs  = rs
366 take_unsafe_UInt_append m  ls rs  =
367   case ls of
368     []     -> rs
369     (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs
370
371 drop (I# n#) ls
372   | n# <# 0#    = ls
373   | otherwise   = drop# n# ls
374     where
375         drop# :: Int# -> [a] -> [a]
376         drop# 0# xs      = xs
377         drop# _  xs@[]   = xs
378         drop# m# (_:xs)  = drop# (m# -# 1#) xs
379
380 splitAt (I# n#) ls
381   | n# <# 0#    = ([], ls)
382   | otherwise   = splitAt# n# ls
383     where
384         splitAt# :: Int# -> [a] -> ([a], [a])
385         splitAt# 0# xs     = ([], xs)
386         splitAt# _  xs@[]  = (xs, xs)
387         splitAt# m# (x:xs) = (x:xs', xs'')
388           where
389             (xs', xs'') = splitAt# (m# -# 1#) xs
390
391 #endif /* USE_REPORT_PRELUDE */
392
393 -- | 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
394
395 span                    :: (a -> Bool) -> [a] -> ([a],[a])
396 span _ xs@[]            =  (xs, xs)
397 span p xs@(x:xs')
398          | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)
399          | otherwise    =  ([],xs)
400
401 -- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
402
403 break                   :: (a -> Bool) -> [a] -> ([a],[a])
404 #ifdef USE_REPORT_PRELUDE
405 break p                 =  span (not . p)
406 #else
407 -- HBC version (stolen)
408 break _ xs@[]           =  (xs, xs)
409 break p xs@(x:xs')
410            | p x        =  ([],xs)
411            | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)
412 #endif
413
414 -- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
415 -- @xs@ must be finite.
416 reverse                 :: [a] -> [a]
417 #ifdef USE_REPORT_PRELUDE
418 reverse                 =  foldl (flip (:)) []
419 #else
420 reverse l =  rev l []
421   where
422     rev []     a = a
423     rev (x:xs) a = rev xs (x:a)
424 #endif
425
426 -- | 'and' returns the conjunction of a Boolean list.  For the result to be
427 -- 'True', the list must be finite; 'False', however, results from a 'False'
428 -- value at a finite index of a finite or infinite list.
429 and                     :: [Bool] -> Bool
430
431 -- | 'or' returns the disjunction of a Boolean list.  For the result to be
432 -- 'False', the list must be finite; 'True', however, results from a 'True'
433 -- value at a finite index of a finite or infinite list.
434 or                      :: [Bool] -> Bool
435 #ifdef USE_REPORT_PRELUDE
436 and                     =  foldr (&&) True
437 or                      =  foldr (||) False
438 #else
439 and []          =  True
440 and (x:xs)      =  x && and xs
441 or []           =  False
442 or (x:xs)       =  x || or xs
443
444 {-# RULES
445 "and/build"     forall (g::forall b.(Bool->b->b)->b->b) . 
446                 and (build g) = g (&&) True
447 "or/build"      forall (g::forall b.(Bool->b->b)->b->b) . 
448                 or (build g) = g (||) False
449  #-}
450 #endif
451
452 -- | Applied to a predicate and a list, 'any' determines if any element
453 -- of the list satisfies the predicate.
454 any                     :: (a -> Bool) -> [a] -> Bool
455
456 -- | Applied to a predicate and a list, 'all' determines if all elements
457 -- of the list satisfy the predicate.
458 all                     :: (a -> Bool) -> [a] -> Bool
459 #ifdef USE_REPORT_PRELUDE
460 any p                   =  or . map p
461 all p                   =  and . map p
462 #else
463 any _ []        = False
464 any p (x:xs)    = p x || any p xs
465
466 all _ []        =  True
467 all p (x:xs)    =  p x && all p xs
468 {-# RULES
469 "any/build"     forall p (g::forall b.(a->b->b)->b->b) . 
470                 any p (build g) = g ((||) . p) False
471 "all/build"     forall p (g::forall b.(a->b->b)->b->b) . 
472                 all p (build g) = g ((&&) . p) True
473  #-}
474 #endif
475
476 -- | 'elem' is the list membership predicate, usually written in infix form,
477 -- e.g., @x `elem` xs@.
478 elem                    :: (Eq a) => a -> [a] -> Bool
479
480 -- | 'notElem' is the negation of 'elem'.
481 notElem                 :: (Eq a) => a -> [a] -> Bool
482 #ifdef USE_REPORT_PRELUDE
483 elem x                  =  any (== x)
484 notElem x               =  all (/= x)
485 #else
486 elem _ []       = False
487 elem x (y:ys)   = x==y || elem x ys
488
489 notElem _ []    =  True
490 notElem x (y:ys)=  x /= y && notElem x ys
491 #endif
492
493 -- | 'lookup' @key assocs@ looks up a key in an association list.
494 lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b
495 lookup _key []          =  Nothing
496 lookup  key ((x,y):xys)
497     | key == x          =  Just y
498     | otherwise         =  lookup key xys
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}