add advice on avoiding import ambiguities
[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  :  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" and "Data.List"
14 -- functions of the same names from lists to any 'Foldable' functor.
15 -- To avoid ambiguity, either import the "Prelude" and "Data.List"
16 -- hiding these names or qualify uses of these function names with an
17 -- alias 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         traverse_,
29         mapM_,
30         sequenceA_,
31         sequence_,
32         -- ** Specialized folds
33         toList,
34         concat,
35         concatMap,
36         and,
37         or,
38         any,
39         all,
40         sum,
41         product,
42         maximum,
43         maximumBy,
44         minimum,
45         minimumBy,
46         -- ** Searches
47         elem,
48         notElem,
49         find
50         ) where
51
52 import Prelude hiding (foldl, foldr, foldl1, foldr1, mapM_, sequence_,
53                 elem, notElem, concat, concatMap, and, or, any, all,
54                 sum, product, maximum, minimum)
55 import qualified Prelude (foldl, foldr, foldl1, foldr1)
56 import Control.Applicative
57 import Data.Maybe (fromMaybe, listToMaybe)
58 import Data.Monoid
59 import Data.Array
60
61 #ifdef __GLASGOW_HASKELL__
62 import GHC.Exts (build)
63 #endif
64
65 -- | Data structures that can be folded.
66 --
67 -- Minimal complete definition: 'foldMap' or 'foldr'.
68 --
69 -- For example, given a data type
70 --
71 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
72 --
73 -- a suitable instance would be
74 --
75 -- > instance Foldable Tree
76 -- >    foldMap f Empty = mempty
77 -- >    foldMap f (Leaf x) = f x
78 -- >    foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
79 --
80 -- This is suitable even for abstract types, as the monoid is assumed
81 -- to satisfy the monoid laws.
82 --
83 class Foldable t where
84         -- | Combine the elements of a structure using a monoid.
85         fold :: Monoid m => t m -> m
86         fold = foldMap id
87
88         -- | Map each element of the structure to a monoid,
89         -- and combine the results.
90         foldMap :: Monoid m => (a -> m) -> t a -> m
91         foldMap f = foldr (mappend . f) mempty
92
93         -- | Right-associative fold of a structure.
94         --
95         -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@
96         foldr :: (a -> b -> b) -> b -> t a -> b
97         foldr f z t = appEndo (foldMap (Endo . f) t) z
98
99         -- | Left-associative fold of a structure.
100         --
101         -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@
102         foldl :: (a -> b -> a) -> a -> t b -> a
103         foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
104
105         -- | A variant of 'foldr' that has no base case,
106         -- and thus may only be applied to non-empty structures.
107         --
108         -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@
109         foldr1 :: (a -> a -> a) -> t a -> a
110         foldr1 f xs = fromMaybe (error "foldr1: empty structure")
111                         (foldr mf Nothing xs)
112           where mf x Nothing = Just x
113                 mf x (Just y) = Just (f x y)
114
115         -- | A variant of 'foldl' that has no base case,
116         -- and thus may only be applied to non-empty structures.
117         --
118         -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@
119         foldl1 :: (a -> a -> a) -> t a -> a
120         foldl1 f xs = fromMaybe (error "foldl1: empty structure")
121                         (foldl mf Nothing xs)
122           where mf Nothing y = Just y
123                 mf (Just x) y = Just (f x y)
124
125 -- instances for Prelude types
126
127 instance Foldable Maybe where
128         foldr f z Nothing = z
129         foldr f z (Just x) = f x z
130
131         foldl f z Nothing = z
132         foldl f z (Just x) = f z x
133
134 instance Foldable [] where
135         foldr = Prelude.foldr
136         foldl = Prelude.foldl
137         foldr1 = Prelude.foldr1
138         foldl1 = Prelude.foldl1
139
140 instance Ix i => Foldable (Array i) where
141         foldr f z = Prelude.foldr f z . elems
142
143 -- | Fold over the elements of a structure,
144 -- associating to the right, but strictly.
145 foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b
146 foldr' f z xs = foldl f' id xs z
147   where f' k x z = k $! f x z
148
149 -- | Monadic fold over the elements of a structure,
150 -- associating to the right, i.e. from right to left.
151 foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
152 foldrM f z xs = foldl f' return xs z
153   where f' k x z = f x z >>= k
154
155 -- | Fold over the elements of a structure,
156 -- associating to the left, but strictly.
157 foldl' :: Foldable t => (a -> b -> a) -> a -> t b -> a
158 foldl' f z xs = foldr f' id xs z
159   where f' x k z = k $! f z x
160
161 -- | Monadic fold over the elements of a structure,
162 -- associating to the left, i.e. from left to right.
163 foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
164 foldlM f z xs = foldr f' return xs z
165   where f' x k z = f z x >>= k
166
167 -- | Map each element of a structure to an action, evaluate
168 -- these actions from left to right, and ignore the results.
169 traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
170 traverse_ f = foldr ((*>) . f) (pure ())
171
172 -- | Map each element of a structure to an monadic action, evaluate
173 -- these actions from left to right, and ignore the results.
174 mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
175 mapM_ f = foldr ((>>) . f) (return ())
176
177 -- | Evaluate each action in the structure from left to right,
178 -- and ignore the results.
179 sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
180 sequenceA_ = foldr (*>) (pure ())
181
182 -- | Evaluate each monadic action in the structure from left to right,
183 -- and ignore the results.
184 sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
185 sequence_ = foldr (>>) (return ())
186
187 -- These use foldr rather than foldMap to avoid repeated concatenation.
188
189 -- | List of elements of a structure.
190 toList :: Foldable t => t a -> [a]
191 #ifdef __GLASGOW_HASKELL__
192 toList t = build (\ c n -> foldr c n t)
193 #else
194 toList = foldr (:) []
195 #endif
196
197 -- | The concatenation of all the elements of a container of lists.
198 concat :: Foldable t => t [a] -> [a]
199 concat = foldr (++) []
200
201 concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
202 concatMap f = foldr ((++) . f) []
203
204 -- | 'and' returns the conjunction of a container of Bools.  For the
205 -- result to be 'True', the container must be finite; 'False', however,
206 -- results from a 'False' value finitely far from the left end.
207 and :: Foldable t => t Bool -> Bool
208 and = getAll . foldMap All
209
210 -- | 'or' returns the disjunction of a container of Bools.  For the
211 -- result to be 'False', the container must be finite; 'True', however,
212 -- results from a 'True' value finitely far from the left end.
213 or :: Foldable t => t Bool -> Bool
214 or = getAny . foldMap Any
215
216 -- | Determines whether any element of the structure satisfies the predicate.
217 any :: Foldable t => (a -> Bool) -> t a -> Bool
218 any p = getAny . foldMap (Any . p)
219
220 -- | Determines whether all elements of the structure satisfy the predicate.
221 all :: Foldable t => (a -> Bool) -> t a -> Bool
222 all p = getAll . foldMap (All . p)
223
224 -- | The 'sum' function computes the sum of the numbers of a structure.
225 sum :: (Foldable t, Num a) => t a -> a
226 sum = getSum . foldMap Sum
227
228 -- | The 'product' function computes the product of the numbers of a structure.
229 product :: (Foldable t, Num a) => t a -> a
230 product = getProduct . foldMap Product
231
232 -- | The largest element of the structure.
233 maximum :: (Foldable t, Ord a) => t a -> a
234 maximum = foldr1 max
235
236 maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
237 maximumBy cmp = foldr1 max'
238   where max' x y = case cmp x y of
239                         GT -> x
240                         _  -> y
241
242 -- | The least element of the structure.
243 minimum :: (Foldable t, Ord a) => t a -> a
244 minimum = foldr1 min
245
246 minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
247 minimumBy cmp = foldr1 min'
248   where min' x y = case cmp x y of
249                         GT -> y
250                         _  -> x
251
252 -- | Does the element occur in the structure?
253 elem :: (Foldable t, Eq a) => a -> t a -> Bool
254 elem = any . (==)
255
256 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
257 notElem x = not . elem x
258
259 -- | The 'find' function takes a predicate and a structure and returns
260 -- the leftmost element of the structure matching the predicate, or
261 -- 'Nothing' if there is no such element.
262 find :: Foldable t => (a -> Bool) -> t a -> Maybe a
263 find p = listToMaybe . concatMap (\ x -> if p x then [x] else [])