Add an INLINE pragme for fmapDefault
[ghc-base.git] / Data / Foldable.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Foldable
4 -- Copyright   :  Ross Paterson 2005
5 -- License     :  BSD-style (see the LICENSE file in the distribution)
6 --
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  portable
10 --
11 -- Class of data structures that can be folded to a summary value.
12 --
13 -- Many of these functions generalize "Prelude", "Control.Monad" and
14 -- "Data.List" functions of the same names from lists to any 'Foldable'
15 -- functor.  To avoid ambiguity, either import those modules hiding
16 -- these names or qualify uses of these function names with an alias
17 -- for this module.
18
19 module Data.Foldable (
20         -- * Folds
21         Foldable(..),
22         -- ** Special biased folds
23         foldr',
24         foldl',
25         foldrM,
26         foldlM,
27         -- ** Folding actions
28         -- *** Applicative actions
29         traverse_,
30         for_,
31         sequenceA_,
32         asum,
33         -- *** Monadic actions
34         mapM_,
35         forM_,
36         sequence_,
37         msum,
38         -- ** Specialized folds
39         toList,
40         concat,
41         concatMap,
42         and,
43         or,
44         any,
45         all,
46         sum,
47         product,
48         maximum,
49         maximumBy,
50         minimum,
51         minimumBy,
52         -- ** Searches
53         elem,
54         notElem,
55         find
56         ) where
57
58 import Prelude hiding (foldl, foldr, foldl1, foldr1, mapM_, sequence_,
59                 elem, notElem, concat, concatMap, and, or, any, all,
60                 sum, product, maximum, minimum)
61 import qualified Prelude (foldl, foldr, foldl1, foldr1)
62 import Control.Applicative
63 import Control.Monad (MonadPlus(..))
64 import Data.Maybe (fromMaybe, listToMaybe)
65 import Data.Monoid
66
67 #ifdef __NHC__
68 import Control.Arrow (ArrowZero(..)) -- work around nhc98 typechecker problem
69 #endif
70
71 #ifdef __GLASGOW_HASKELL__
72 import GHC.Exts (build)
73 #endif
74
75 #if defined(__GLASGOW_HASKELL__)
76 import GHC.Arr
77 #elif defined(__HUGS__)
78 import Hugs.Array
79 #elif defined(__NHC__)
80 import Array
81 #endif
82
83 -- | Data structures that can be folded.
84 --
85 -- Minimal complete definition: 'foldMap' or 'foldr'.
86 --
87 -- For example, given a data type
88 --
89 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
90 --
91 -- a suitable instance would be
92 --
93 -- > instance Foldable Tree where
94 -- >    foldMap f Empty = mempty
95 -- >    foldMap f (Leaf x) = f x
96 -- >    foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
97 --
98 -- This is suitable even for abstract types, as the monoid is assumed
99 -- to satisfy the monoid laws.  Alternatively, one could define @foldr@:
100 --
101 -- > instance Foldable Tree where
102 -- >    foldr f z Empty = z
103 -- >    foldr f z (Leaf x) = f x z
104 -- >    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
105 --
106 class Foldable t where
107         -- | Combine the elements of a structure using a monoid.
108         fold :: Monoid m => t m -> m
109         fold = foldMap id
110
111         -- | Map each element of the structure to a monoid,
112         -- and combine the results.
113         foldMap :: Monoid m => (a -> m) -> t a -> m
114         foldMap f = foldr (mappend . f) mempty
115
116         -- | Right-associative fold of a structure.
117         --
118         -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@
119         foldr :: (a -> b -> b) -> b -> t a -> b
120         foldr f z t = appEndo (foldMap (Endo . f) t) z
121
122         -- | Left-associative fold of a structure.
123         --
124         -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@
125         foldl :: (a -> b -> a) -> a -> t b -> a
126         foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
127
128         -- | A variant of 'foldr' that has no base case,
129         -- and thus may only be applied to non-empty structures.
130         --
131         -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@
132         foldr1 :: (a -> a -> a) -> t a -> a
133         foldr1 f xs = fromMaybe (error "foldr1: empty structure")
134                         (foldr mf Nothing xs)
135           where mf x Nothing = Just x
136                 mf x (Just y) = Just (f x y)
137
138         -- | A variant of 'foldl' that has no base case,
139         -- and thus may only be applied to non-empty structures.
140         --
141         -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@
142         foldl1 :: (a -> a -> a) -> t a -> a
143         foldl1 f xs = fromMaybe (error "foldl1: empty structure")
144                         (foldl mf Nothing xs)
145           where mf Nothing y = Just y
146                 mf (Just x) y = Just (f x y)
147
148 -- instances for Prelude types
149
150 instance Foldable Maybe where
151         foldr _ z Nothing = z
152         foldr f z (Just x) = f x z
153
154         foldl _ z Nothing = z
155         foldl f z (Just x) = f z x
156
157 instance Foldable [] where
158         foldr = Prelude.foldr
159         foldl = Prelude.foldl
160         foldr1 = Prelude.foldr1
161         foldl1 = Prelude.foldl1
162
163 instance Ix i => Foldable (Array i) where
164         foldr f z = Prelude.foldr f z . elems
165         foldl f z = Prelude.foldl f z . elems
166         foldr1 f = Prelude.foldr1 f . elems
167         foldl1 f = Prelude.foldl1 f . elems
168
169 -- | Fold over the elements of a structure,
170 -- associating to the right, but strictly.
171 foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b
172 foldr' f z0 xs = foldl f' id xs z0
173   where f' k x z = k $! f x z
174
175 -- | Monadic fold over the elements of a structure,
176 -- associating to the right, i.e. from right to left.
177 foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
178 foldrM f z0 xs = foldl f' return xs z0
179   where f' k x z = f x z >>= k
180
181 -- | Fold over the elements of a structure,
182 -- associating to the left, but strictly.
183 foldl' :: Foldable t => (a -> b -> a) -> a -> t b -> a
184 foldl' f z0 xs = foldr f' id xs z0
185   where f' x k z = k $! f z x
186
187 -- | Monadic fold over the elements of a structure,
188 -- associating to the left, i.e. from left to right.
189 foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
190 foldlM f z0 xs = foldr f' return xs z0
191   where f' x k z = f z x >>= k
192
193 -- | Map each element of a structure to an action, evaluate
194 -- these actions from left to right, and ignore the results.
195 traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
196 traverse_ f = foldr ((*>) . f) (pure ())
197
198 -- | 'for_' is 'traverse_' with its arguments flipped.
199 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
200 {-# INLINE for_ #-}
201 for_ = flip traverse_
202
203 -- | Map each element of a structure to a monadic action, evaluate
204 -- these actions from left to right, and ignore the results.
205 mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
206 mapM_ f = foldr ((>>) . f) (return ())
207
208 -- | 'forM_' is 'mapM_' with its arguments flipped.
209 forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
210 {-# INLINE forM_ #-}
211 forM_ = flip mapM_
212
213 -- | Evaluate each action in the structure from left to right,
214 -- and ignore the results.
215 sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
216 sequenceA_ = foldr (*>) (pure ())
217
218 -- | Evaluate each monadic action in the structure from left to right,
219 -- and ignore the results.
220 sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
221 sequence_ = foldr (>>) (return ())
222
223 -- | The sum of a collection of actions, generalizing 'concat'.
224 asum :: (Foldable t, Alternative f) => t (f a) -> f a
225 {-# INLINE asum #-}
226 asum = foldr (<|>) empty
227
228 -- | The sum of a collection of actions, generalizing 'concat'.
229 msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
230 {-# INLINE msum #-}
231 msum = foldr mplus mzero
232
233 -- These use foldr rather than foldMap to avoid repeated concatenation.
234
235 -- | List of elements of a structure.
236 toList :: Foldable t => t a -> [a]
237 {-# INLINE toList #-}
238 #ifdef __GLASGOW_HASKELL__
239 toList t = build (\ c n -> foldr c n t)
240 #else
241 toList = foldr (:) []
242 #endif
243
244 -- | The concatenation of all the elements of a container of lists.
245 concat :: Foldable t => t [a] -> [a]
246 concat = fold
247
248 -- | Map a function over all the elements of a container and concatenate
249 -- the resulting lists.
250 concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
251 concatMap = foldMap
252
253 -- | 'and' returns the conjunction of a container of Bools.  For the
254 -- result to be 'True', the container must be finite; 'False', however,
255 -- results from a 'False' value finitely far from the left end.
256 and :: Foldable t => t Bool -> Bool
257 and = getAll . foldMap All
258
259 -- | 'or' returns the disjunction of a container of Bools.  For the
260 -- result to be 'False', the container must be finite; 'True', however,
261 -- results from a 'True' value finitely far from the left end.
262 or :: Foldable t => t Bool -> Bool
263 or = getAny . foldMap Any
264
265 -- | Determines whether any element of the structure satisfies the predicate.
266 any :: Foldable t => (a -> Bool) -> t a -> Bool
267 any p = getAny . foldMap (Any . p)
268
269 -- | Determines whether all elements of the structure satisfy the predicate.
270 all :: Foldable t => (a -> Bool) -> t a -> Bool
271 all p = getAll . foldMap (All . p)
272
273 -- | The 'sum' function computes the sum of the numbers of a structure.
274 sum :: (Foldable t, Num a) => t a -> a
275 sum = getSum . foldMap Sum
276
277 -- | The 'product' function computes the product of the numbers of a structure.
278 product :: (Foldable t, Num a) => t a -> a
279 product = getProduct . foldMap Product
280
281 -- | The largest element of a non-empty structure.
282 maximum :: (Foldable t, Ord a) => t a -> a
283 maximum = foldr1 max
284
285 -- | The largest element of a non-empty structure with respect to the
286 -- given comparison function.
287 maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
288 maximumBy cmp = foldr1 max'
289   where max' x y = case cmp x y of
290                         GT -> x
291                         _  -> y
292
293 -- | The least element of a non-empty structure.
294 minimum :: (Foldable t, Ord a) => t a -> a
295 minimum = foldr1 min
296
297 -- | The least element of a non-empty structure with respect to the
298 -- given comparison function.
299 minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
300 minimumBy cmp = foldr1 min'
301   where min' x y = case cmp x y of
302                         GT -> y
303                         _  -> x
304
305 -- | Does the element occur in the structure?
306 elem :: (Foldable t, Eq a) => a -> t a -> Bool
307 elem = any . (==)
308
309 -- | 'notElem' is the negation of 'elem'.
310 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
311 notElem x = not . elem x
312
313 -- | The 'find' function takes a predicate and a structure and returns
314 -- the leftmost element of the structure matching the predicate, or
315 -- 'Nothing' if there is no such element.
316 find :: Foldable t => (a -> Bool) -> t a -> Maybe a
317 find p = listToMaybe . concatMap (\ x -> if p x then [x] else [])