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