1 -----------------------------------------------------------------------------
3 -- Module : Data.Foldable
4 -- Copyright : Ross Paterson 2005
5 -- License : BSD-style (see the LICENSE file in the distribution)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- Class of data structures that can be folded to a summary value.
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
19 module Data.Foldable (
22 -- ** Special biased folds
28 -- *** Applicative actions
33 -- *** Monadic actions
38 -- ** Specialized folds
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)
68 import Control.Arrow (ArrowZero(..)) -- work around nhc98 typechecker problem
71 #ifdef __GLASGOW_HASKELL__
72 import GHC.Exts (build)
75 #if defined(__GLASGOW_HASKELL__)
77 #elif defined(__HUGS__)
79 #elif defined(__NHC__)
83 -- | Data structures that can be folded.
85 -- Minimal complete definition: 'foldMap' or 'foldr'.
87 -- For example, given a data type
89 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
91 -- a suitable instance would be
93 -- > instance Foldable Tree
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
98 -- This is suitable even for abstract types, as the monoid is assumed
99 -- to satisfy the monoid laws.
101 class Foldable t where
102 -- | Combine the elements of a structure using a monoid.
103 fold :: Monoid m => t m -> m
106 -- | Map each element of the structure to a monoid,
107 -- and combine the results.
108 foldMap :: Monoid m => (a -> m) -> t a -> m
109 foldMap f = foldr (mappend . f) mempty
111 -- | Right-associative fold of a structure.
113 -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@
114 foldr :: (a -> b -> b) -> b -> t a -> b
115 foldr f z t = appEndo (foldMap (Endo . f) t) z
117 -- | Left-associative fold of a structure.
119 -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@
120 foldl :: (a -> b -> a) -> a -> t b -> a
121 foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
123 -- | A variant of 'foldr' that has no base case,
124 -- and thus may only be applied to non-empty structures.
126 -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@
127 foldr1 :: (a -> a -> a) -> t a -> a
128 foldr1 f xs = fromMaybe (error "foldr1: empty structure")
129 (foldr mf Nothing xs)
130 where mf x Nothing = Just x
131 mf x (Just y) = Just (f x y)
133 -- | A variant of 'foldl' that has no base case,
134 -- and thus may only be applied to non-empty structures.
136 -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@
137 foldl1 :: (a -> a -> a) -> t a -> a
138 foldl1 f xs = fromMaybe (error "foldl1: empty structure")
139 (foldl mf Nothing xs)
140 where mf Nothing y = Just y
141 mf (Just x) y = Just (f x y)
143 -- instances for Prelude types
145 instance Foldable Maybe where
146 foldr _ z Nothing = z
147 foldr f z (Just x) = f x z
149 foldl _ z Nothing = z
150 foldl f z (Just x) = f z x
152 instance Foldable [] where
153 foldr = Prelude.foldr
154 foldl = Prelude.foldl
155 foldr1 = Prelude.foldr1
156 foldl1 = Prelude.foldl1
158 instance Ix i => Foldable (Array i) where
159 foldr f z = Prelude.foldr f z . elems
161 -- | Fold over the elements of a structure,
162 -- associating to the right, but strictly.
163 foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b
164 foldr' f z0 xs = foldl f' id xs z0
165 where f' k x z = k $! f x z
167 -- | Monadic fold over the elements of a structure,
168 -- associating to the right, i.e. from right to left.
169 foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
170 foldrM f z0 xs = foldl f' return xs z0
171 where f' k x z = f x z >>= k
173 -- | Fold over the elements of a structure,
174 -- associating to the left, but strictly.
175 foldl' :: Foldable t => (a -> b -> a) -> a -> t b -> a
176 foldl' f z0 xs = foldr f' id xs z0
177 where f' x k z = k $! f z x
179 -- | Monadic fold over the elements of a structure,
180 -- associating to the left, i.e. from left to right.
181 foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
182 foldlM f z0 xs = foldr f' return xs z0
183 where f' x k z = f z x >>= k
185 -- | Map each element of a structure to an action, evaluate
186 -- these actions from left to right, and ignore the results.
187 traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
188 traverse_ f = foldr ((*>) . f) (pure ())
190 -- | 'for_' is 'traverse_' with its arguments flipped.
191 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
193 for_ = flip traverse_
195 -- | Map each element of a structure to a monadic action, evaluate
196 -- these actions from left to right, and ignore the results.
197 mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
198 mapM_ f = foldr ((>>) . f) (return ())
200 -- | 'forM_' is 'mapM_' with its arguments flipped.
201 forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
205 -- | Evaluate each action in the structure from left to right,
206 -- and ignore the results.
207 sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
208 sequenceA_ = foldr (*>) (pure ())
210 -- | Evaluate each monadic action in the structure from left to right,
211 -- and ignore the results.
212 sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
213 sequence_ = foldr (>>) (return ())
215 -- | The sum of a collection of actions, generalizing 'concat'.
216 asum :: (Foldable t, Alternative f) => t (f a) -> f a
218 asum = foldr (<|>) empty
220 -- | The sum of a collection of actions, generalizing 'concat'.
221 msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
223 msum = foldr mplus mzero
225 -- These use foldr rather than foldMap to avoid repeated concatenation.
227 -- | List of elements of a structure.
228 toList :: Foldable t => t a -> [a]
229 {-# INLINE toList #-}
230 #ifdef __GLASGOW_HASKELL__
231 toList t = build (\ c n -> foldr c n t)
233 toList = foldr (:) []
236 -- | The concatenation of all the elements of a container of lists.
237 concat :: Foldable t => t [a] -> [a]
240 -- | Map a function over all the elements of a container and concatenate
241 -- the resulting lists.
242 concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
245 -- | 'and' returns the conjunction of a container of Bools. For the
246 -- result to be 'True', the container must be finite; 'False', however,
247 -- results from a 'False' value finitely far from the left end.
248 and :: Foldable t => t Bool -> Bool
249 and = getAll . foldMap All
251 -- | 'or' returns the disjunction of a container of Bools. For the
252 -- result to be 'False', the container must be finite; 'True', however,
253 -- results from a 'True' value finitely far from the left end.
254 or :: Foldable t => t Bool -> Bool
255 or = getAny . foldMap Any
257 -- | Determines whether any element of the structure satisfies the predicate.
258 any :: Foldable t => (a -> Bool) -> t a -> Bool
259 any p = getAny . foldMap (Any . p)
261 -- | Determines whether all elements of the structure satisfy the predicate.
262 all :: Foldable t => (a -> Bool) -> t a -> Bool
263 all p = getAll . foldMap (All . p)
265 -- | The 'sum' function computes the sum of the numbers of a structure.
266 sum :: (Foldable t, Num a) => t a -> a
267 sum = getSum . foldMap Sum
269 -- | The 'product' function computes the product of the numbers of a structure.
270 product :: (Foldable t, Num a) => t a -> a
271 product = getProduct . foldMap Product
273 -- | The largest element of a non-empty structure.
274 maximum :: (Foldable t, Ord a) => t a -> a
277 -- | The largest element of a non-empty structure with respect to the
278 -- given comparison function.
279 maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
280 maximumBy cmp = foldr1 max'
281 where max' x y = case cmp x y of
285 -- | The least element of a non-empty structure.
286 minimum :: (Foldable t, Ord a) => t a -> a
289 -- | The least element of a non-empty structure with respect to the
290 -- given comparison function.
291 minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
292 minimumBy cmp = foldr1 min'
293 where min' x y = case cmp x y of
297 -- | Does the element occur in the structure?
298 elem :: (Foldable t, Eq a) => a -> t a -> Bool
301 -- | 'notElem' is the negation of 'elem'.
302 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
303 notElem x = not . elem x
305 -- | The 'find' function takes a predicate and a structure and returns
306 -- the leftmost element of the structure matching the predicate, or
307 -- 'Nothing' if there is no such element.
308 find :: Foldable t => (a -> Bool) -> t a -> Maybe a
309 find p = listToMaybe . concatMap (\ x -> if p x then [x] else [])