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