1 -----------------------------------------------------------------------------
3 -- Module : Data.Foldable
4 -- Copyright : Ross Paterson 2005
5 -- License : BSD-style (see the LICENSE file in the distribution)
7 -- Maintainer : ross@soi.city.ac.uk
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" 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.
19 module Data.Foldable (
22 -- ** Special biased folds
32 -- ** Specialized folds
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)
61 #ifdef __GLASGOW_HASKELL__
62 import GHC.Exts (build)
65 -- | Data structures that can be folded.
67 -- Minimal complete definition: 'foldMap' or 'foldr'.
69 -- For example, given a data type
71 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
73 -- a suitable instance would be
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
80 -- This is suitable even for abstract types, as the monoid is assumed
81 -- to satisfy the monoid laws.
83 class Foldable t where
84 -- | Combine the elements of a structure using a monoid.
85 fold :: Monoid m => t m -> m
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
93 -- | Right-associative fold of a structure.
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
99 -- | Left-associative fold of a structure.
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
105 -- | A variant of 'foldr' that has no base case,
106 -- and thus may only be applied to non-empty structures.
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)
115 -- | A variant of 'foldl' that has no base case,
116 -- and thus may only be applied to non-empty structures.
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)
125 -- instances for Prelude types
127 instance Foldable Maybe where
128 foldr f z Nothing = z
129 foldr f z (Just x) = f x z
131 foldl f z Nothing = z
132 foldl f z (Just x) = f z x
134 instance Foldable [] where
135 foldr = Prelude.foldr
136 foldl = Prelude.foldl
137 foldr1 = Prelude.foldr1
138 foldl1 = Prelude.foldl1
140 instance Ix i => Foldable (Array i) where
141 foldr f z = Prelude.foldr f z . elems
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
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
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
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
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 ())
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 ())
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 ())
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 ())
187 -- These use foldr rather than foldMap to avoid repeated concatenation.
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)
194 toList = foldr (:) []
197 -- | The concatenation of all the elements of a container of lists.
198 concat :: Foldable t => t [a] -> [a]
199 concat = foldr (++) []
201 concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
202 concatMap f = foldr ((++) . f) []
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
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
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)
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)
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
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
232 -- | The largest element of the structure.
233 maximum :: (Foldable t, Ord a) => t a -> a
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
242 -- | The least element of the structure.
243 minimum :: (Foldable t, Ord a) => t a -> a
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
252 -- | Does the element occur in the structure?
253 elem :: (Foldable t, Eq a) => a -> t a -> Bool
256 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
257 notElem x = not . elem x
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 [])