Determines whether all elements of the structure satisfy the predicate.
Examples
Basic usage:
all (> 3) []True
all (> 3) [1,2]False
all (> 3) [1,2,3,4,5]False
all (> 3) [1..]False
all (> 3) [4..]* Hangs forever *
:: a typeCtrl KGHC 10.0.0.20260917 · lts/ghc-10.0.x · fc4e598 · 2026-10-11
Modulebase-compat-batteries-0.15.0Haskell2010
Determines whether all elements of the structure satisfy the predicate.
Basic usage:
all (> 3) []True
all (> 3) [1,2]False
all (> 3) [1,2,3,4,5]False
all (> 3) [1..]False
all (> 3) [4..]* Hangs forever *
and returns the conjunction of a container of Bools. For the result to be True, the container must be finite; False, however, results from a False value finitely far from the left end.
Basic usage:
and []True
and [True]True
and [False]False
and [True, True, False]False
and (False : repeat True) -- Infinite list [False,True,True,True,...False
and (repeat True)* Hangs forever *
Determines whether any element of the structure satisfies the predicate.
Basic usage:
any (> 3) []False
any (> 3) [1,2]False
any (> 3) [1,2,3,4,5]True
any (> 3) [1..]True
any (> 3) [0, -1..]* Hangs forever *
The sum of a collection of actions using (<|>), generalizing concat.
asum is just like msum, but generalised to Alternative.
Basic usage:
asum [Just "Hello", Nothing, Just "World"]Just "Hello"
The concatenation of all the elements of a container of lists.
Basic usage:
concat (Just [1, 2, 3])[1,2,3]
concat (Left 42)[]
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
Map a function over all the elements of a container and concatenate the resulting lists.
Basic usage:
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
concatMap (take 3) (Just [1..])[1,2,3]
Left-to-right monadic fold over the elements of a structure.
Given a structure t with elements (a, b, ..., w, x, y), the result of
a fold with an operator function f is equivalent to:
foldlM f z t = do
aa <- f z a
bb <- f aa b
...
xx <- f ww x
yy <- f xx y
return yy -- Just @return z@ when the structure is emptyFor a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2Another way of thinking about foldlM is that it amounts to an application
to z of a Kleisli composition:
foldlM f z t =
flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ zThe monadic effects of foldlM are sequenced from left to right.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from an initial
segment of the element sequence. If you want to evaluate the monadic
effects in right-to-left order, or perhaps be able to short-circuit after
processing a tail of the sequence of elements, you'll need to use foldrM
instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the rightmost element y, so that, ignoring effects, the result
looks like a left fold:
((((z `f` a) `f` b) ... `f` w) `f` x) `f` yBasic usage:
let f a e = do { print e ; return $ e : a }foldlM f [] [0..3]0123[3,2,1,0]
Right-to-left monadic fold over the elements of a structure.
Given a structure t with elements (a, b, c, ..., x, y), the result of
a fold with an operator function f is equivalent to:
foldrM f z t = do
yy <- f y z
xx <- f x yy
...
bb <- f b cc
aa <- f a bb
return aa -- Just @return z@ when the structure is emptyFor a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2Another way of thinking about foldrM is that it amounts to an application
to z of a Kleisli composition:
foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ zThe monadic effects of foldrM are sequenced from right to left, and e.g.
folds of infinite lists will diverge.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from a tail of the
element sequence. If you want to evaluate the monadic effects in
left-to-right order, or perhaps be able to short-circuit after an initial
sequence of elements, you'll need to use foldlM instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the leftmost element a, so that, ignoring effects, the result
looks like a right fold:
a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).Basic usage:
let f i acc = do { print i ; return $ i : acc }foldrM f [] [0..3]3210[0,1,2,3]
for_ is traverse_ with its arguments flipped. For a version that doesn't ignore the results see for. This is forM_ generalised to Applicative actions.
for_ is just like forM_, but generalised to Applicative actions.
Basic usage:
for_ [1..4] print1234
The largest element of a non-empty structure with respect to the given comparison function. Structure order is used as a tie-breaker: if there are multiple largest elements, the rightmost of them is chosen.
Basic usage:
maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"Longest"
WARNING: This function is partial for possibly-empty structures like lists.
The least element of a non-empty structure with respect to the given comparison function. Structure order is used as a tie-breaker: if there are multiple least elements, the leftmost of them is chosen.
Basic usage:
minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"!"
WARNING: This function is partial for possibly-empty structures like lists.
notElem is the negation of elem.
Basic usage:
3 `notElem` []True
3 `notElem` [1,2]True
3 `notElem` [1,2,3,4,5]False
For infinite structures, notElem terminates if the value exists at a finite distance from the left side of the structure:
3 `notElem` [1..]False
3 `notElem` ([4..] ++ [3])* Hangs forever *
or returns the disjunction of a container of Bools. For the result to be False, the container must be finite; True, however, results from a True value finitely far from the left end.
Basic usage:
or []False
or [True]True
or [False]False
or [True, True, False]True
or (True : repeat False) -- Infinite list [True,False,False,False,...True
or (repeat False)* Hangs forever *
Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see sequenceA.
sequenceA_ is just like sequence_, but generalised to Applicative actions.
Basic usage:
sequenceA_ [print "Hello", print "world", print "!"]"Hello""world""!"
Evaluate each monadic action in the structure from left to right,
and ignore the results. For a version that doesn't ignore the
results see Data.Traversable.sequence.
sequence_ is just like sequenceA_, but specialised to monadic actions.
Map each element of a structure to an Applicative action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see traverse.
traverse_ is just like mapM_, but generalised to Applicative actions.
Basic usage:
traverse_ print ["Hello", "world", "!"]"Hello""world""!"
The Foldable class represents data structures that can be reduced to a summary value one element at a time. Strict left-associative folds are a good fit for space-efficient reduction, while lazy right-associative folds are a good fit for corecursive iteration, or for folds that short-circuit after processing an initial subsequence of the structure's elements.
Instances can be derived automatically by enabling the DeriveFoldable
extension. For example, a derived instance for a binary tree might be:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving FoldableA more detailed description can be found in the Overview section of
Data.Foldable#overview.
For the class laws see the Laws section of Data.Foldable#laws.
fold :: Monoid m => t m -> mGiven a structure with elements whose type is a Monoid, combine them
via the monoid's (<>) operator. This fold is right-associative and
lazy in the accumulator. When you need a strict left-associative fold,
use foldMap' instead, with id as the map.
Basic usage:
fold [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))Sum {getSum = 9}
Folds of unbounded structures do not terminate when the monoid's
(<>) operator is strict:
fold (repeat Nothing)* Hangs forever *
Lazy corecursive folds of unbounded structures are fine:
take 12 $ fold $ map (\i -> [i..i+2]) [0..][0,1,2,1,2,3,2,3,4,3,4,5]sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..]2666668666666
foldMap :: Monoid m => (a -> m) -> t a -> mMap each element of the structure into a monoid, and combine the
results with (<>). This fold is right-associative and lazy in the
accumulator. For strict left-associative folds consider foldMap'
instead.
Basic usage:
foldMap Sum [1, 3, 5]Sum {getSum = 9}
foldMap Product [1, 3, 5]Product {getProduct = 15}
foldMap (replicate 3) [1, 2, 3][1,1,1,2,2,2,3,3,3]
When a Monoid's (<>) is lazy in its second argument, foldMap can
return a result even from an unbounded structure. For example, lazy
accumulation enables Data.ByteString.Builder to efficiently serialise
large data structures and produce the output incrementally:
import qualified Data.ByteString.Lazy as Limport qualified Data.ByteString.Builder as Blet bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20let lbs = B.toLazyByteString $ foldMap bld [0..]L.take 64 lbs"0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24"
foldMap' :: Monoid m => (a -> m) -> t a -> mA left-associative variant of foldMap that is strict in the
accumulator. Use this method for strict reduction when partial
results are merged via (<>).
Define a Monoid over finite bit strings under xor. Use it to
strictly compute the xor of a list of Int values.
:set -XGeneralizedNewtypeDerivingimport Data.Bits (Bits, FiniteBits, xor, zeroBits)import Data.Foldable (foldMap')import Numeric (showHex)newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits)instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b)instance Bits a => Monoid (X a) where mempty = X zeroBitslet bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411](\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits"0x42"
foldr :: (a -> b -> b) -> b -> t a -> bRight-associative fold of a structure, lazy in the accumulator.
In the case of lists, foldr, when applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)Note that since the head of the resulting expression is produced by an application of the operator to the first element of the list, given an operator lazy in its right argument, foldr can produce a terminating expression from an unbounded list.
For a general Foldable structure this should be semantically identical to,
foldr f z = foldr f z . toListBasic usage:
foldr (||) False [False, True, False]True
foldr (||) False []False
foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
⚠️ Applying foldr to infinite structures usually doesn't terminate.
It may still terminate under one of the following conditions:
the folding function is short-circuiting
the folding function is lazy on its second argument
( short-circuits on True values, so the following terminates
because there is a True value finitely far from the left side:||)
foldr (||) False (True : repeat False)True
But the following doesn't terminate:
foldr (||) False (repeat False ++ [True])* Hangs forever *
Applying foldr to infinite structures terminates when the operator is
lazy in its second argument (the initial accumulator is never used in
this case, and so could be left undefined, but [] is more clear):
take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
foldr' :: (a -> b -> b) -> b -> t a -> bfoldr' is a variant of foldr that performs strict reduction from right to left, i.e. starting with the right-most element. The input structure must be finite, otherwise foldr' runs out of space (diverges).
If you want a strict right fold in constant space, you need a structure
that supports faster than O(n) access to the right-most element, such
as Seq from the containers package.
This method does not run in constant space for structures such as lists that don't support efficient right-to-left iteration and so require O(n) space to perform right-to-left reduction. Use of this method with such a structure is a hint that the chosen structure may be a poor fit for the task at hand. If the order in which the elements are combined is not important, use foldl' instead.
foldl :: (b -> a -> b) -> b -> t a -> bLeft-associative fold of a structure, lazy in the accumulator. This is rarely what you want, but can work well for structures with efficient right-to-left sequencing and an operator that is lazy in its left argument.
In the case of lists, foldl, when applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right:
foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xnNote that to produce the outermost application of the operator the entire input list must be traversed. Like all left-associative folds, foldl will diverge if given an infinite list.
If you want an efficient strict left-fold, you probably want to use
foldl' instead of foldl. The reason for this is that the latter
does not force the inner results (e.g. z `f` x1 in the above
example) before applying them to the operator (e.g. to (`f` x2)).
This results in a thunk chain O(n) elements long, which then must be
evaluated from the outside-in.
For a general Foldable structure this should be semantically identical to:
foldl f z = foldl f z . toListThe first example is a strict fold, which in practice is best performed with foldl'.
foldl (+) 42 [1,2,3,4]52
Though the result below is lazy, the input is reversed before prepending it to the initial accumulator, so corecursion begins only after traversing the entire input string.
foldl (\acc c -> c : acc) "abcd" "efgh""hgfeabcd"
A left fold of a structure that is infinite on the right cannot terminate, even when for any finite input the fold just returns the initial accumulator:
foldl (\a _ -> a) 0 $ repeat 1* Hangs forever *
WARNING: When it comes to lists, you always want to use either foldl' or foldr instead.
foldl' :: (b -> a -> b) -> b -> t a -> bLeft-associative fold of a structure but with strict application of the operator.
This ensures that each step of the fold is forced to Weak Head Normal Form before being applied, avoiding the collection of thunks that would otherwise occur. This is often what you want to strictly reduce a finite structure to a single strict result (e.g. sum).
For a general Foldable structure this should be semantically identical to,
foldl' f z = foldl' f z . toListfoldr1 :: (a -> a -> a) -> t a -> aA variant of foldr that has no base case, and thus may only be applied to non-empty structures.
This function is non-total and will raise a runtime exception if the structure happens to be empty.
Basic usage:
foldr1 (+) [1..4]10
foldr1 (+) []Exception: Prelude.foldr1: empty list
foldr1 (+) Nothing*** Exception: foldr1: empty structure
foldr1 (-) [1..4]-2
foldr1 (&&) [True, False, True, True]False
foldr1 (||) [False, False, True, True]True
foldr1 (+) [1..]* Hangs forever *
foldl1 :: (a -> a -> a) -> t a -> aA variant of foldl that has no base case, and thus may only be applied to non-empty structures.
This function is non-total and will raise a runtime exception if the structure happens to be empty.
foldl1 f = foldl1 f . toListBasic usage:
foldl1 (+) [1..4]10
foldl1 (+) []*** Exception: Prelude.foldl1: empty list
foldl1 (+) Nothing*** Exception: foldl1: empty structure
foldl1 (-) [1..4]-8
foldl1 (&&) [True, False, True, True]False
foldl1 (||) [False, False, True, True]True
foldl1 (+) [1..]* Hangs forever *
toList :: t a -> [a]List of elements of a structure, from left to right. If the entire list is intended to be reduced via a fold, just fold the structure directly bypassing the list.
Basic usage:
toList Nothing[]
toList (Just 42)[42]
toList (Left "foo")[]
toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8)))[5,17,12,8]
For lists, toList is the identity:
toList [1, 2, 3][1,2,3]
null :: t a -> BoolTest whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.
Basic usage:
null []True
null [1]False
null is expected to terminate even for infinite structures. The default implementation terminates provided the structure is bounded on the left (there is a leftmost element).
null [1..]False
length :: t a -> IntReturns the size/length of a finite structure as an Int. The default implementation just counts elements starting with the leftmost. Instances for structures that can compute the element count faster than via element-by-element counting, should provide a specialised implementation.
Basic usage:
length []0
length ['a', 'b', 'c']3length [1..]* Hangs forever *
elem :: Eq a => a -> t a -> Boolinfix 4Does the element occur in the structure?
Note: elem is often used in infix form.
Basic usage:
3 `elem` []False
3 `elem` [1,2]False
3 `elem` [1,2,3,4,5]True
For infinite structures, the default implementation of elem terminates if the sought-after value exists at a finite distance from the left side of the structure:
3 `elem` [1..]True
3 `elem` ([4..] ++ [3])* Hangs forever *
maximum :: Ord a => t a -> aThe largest element of a non-empty structure. This function is
equivalent to foldr1 max, and its behavior on structures with
multiple largest elements depends on the relevant implementation of
max. For the default implementation of max (max x y = if x <= y
then y else x), structure order is used as a tie-breaker: if there are
multiple largest elements, the rightmost of them is chosen (this is
equivalent to maximumBy compare).
This function is non-total and will raise a runtime exception if the structure happens to be empty. A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the maximum in faster than linear time.
Basic usage:
maximum [1..10]10
maximum []*** Exception: Prelude.maximum: empty list
maximum Nothing*** Exception: maximum: empty structure
WARNING: This function is partial for possibly-empty structures like lists.
minimum :: Ord a => t a -> aThe least element of a non-empty structure. This function is
equivalent to foldr1 min, and its behavior on structures with
multiple largest elements depends on the relevant implementation of
min. For the default implementation of min (min x y = if x <= y
then x else y), structure order is used as a tie-breaker: if there are
multiple least elements, the leftmost of them is chosen (this is
equivalent to minimumBy compare).
This function is non-total and will raise a runtime exception if the structure happens to be empty. A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the minimum in faster than linear time.
Basic usage:
minimum [1..10]1
minimum []*** Exception: Prelude.minimum: empty list
minimum Nothing*** Exception: minimum: empty structure
WARNING: This function is partial for possibly-empty structures like lists.
sum :: Num a => t a -> aThe sum function computes the sum of the numbers of a structure.
Basic usage:
sum []0
sum [42]42
sum [1..10]55
sum [4.1, 2.0, 1.7]7.8
sum [1..]* Hangs forever *
product :: Num a => t a -> aThe product function computes the product of the numbers of a structure.
Basic usage:
product []1
product [42]42
product [1..10]3628800
product [4.1, 2.0, 1.7]13.939999999999998
product [1..]* Hangs forever *
Foldable ComplexDefined in base-4.23.0.0 · Data.ComplexFoldable FirstDefined in base-4.23.0.0 · Data.SemigroupFoldable LastDefined in base-4.23.0.0 · Data.SemigroupFoldable MaxDefined in base-4.23.0.0 · Data.SemigroupFoldable MinDefined in base-4.23.0.0 · Data.SemigroupFoldable NonEmptyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable IdentityDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.IdentityFoldable FirstDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable LastDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable DownDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable DualDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable ProductDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable SumDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable ZipListDefined in ghc-internal-10.0.0 · GHC.Internal.Functor.ZipListFoldable Par1Defined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable GenClosureDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ClosuresFoldable GenStackFieldDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ClosuresFoldable GenStackFrameDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ClosuresFoldable GenStgStackClosureDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ClosuresFoldable MaybeDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable TyVarBndrDefined in ghc-internal-10.0.0 · GHC.Internal.TH.SyntaxFoldable SoloDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable []Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable ProxyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable U1Defined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UAddrDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UCharDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UFloatDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UIntDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable UWordDefined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable V1Defined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable (Arg a)Defined in base-4.23.0.0 · Data.SemigroupFoldable (Array i)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable (Either a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable (Tuple2 a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable (Const m)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.ConstFoldable f => Foldable (Ap f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Alt f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Rec1 f)Defined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable (K1 i c)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics(Foldable f, Foldable g) => Foldable (Product f g)Defined in base-4.23.0.0 · Data.Functor.Product(Foldable f, Foldable g) => Foldable (Sum f g)Defined in base-4.23.0.0 · Data.Functor.Sum(Foldable f, Foldable g) => Foldable (f :*: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics(Foldable f, Foldable g) => Foldable (f :+: g)Defined in ghc-internal-10.0.0 · GHC.Internal.GenericsFoldable f => Foldable (M1 i c f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics(Foldable f, Foldable g) => Foldable (Compose f g)Defined in base-4.23.0.0 · Data.Functor.Compose(Foldable f, Foldable g) => Foldable (f :.: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics