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