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.
Methods
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.Examples
Basic usage:
Example1 expression fold [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
Example1 expression 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:Example1 expression fold (repeat Nothing)* Hangs forever *
Lazy corecursive folds of unbounded structures are fine:
Example2 expressions 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.Examples
Basic usage:
Example1 expression foldMap Sum [1, 3, 5]Sum {getSum = 9}
Example1 expression foldMap Product [1, 3, 5]Product {getProduct = 15}
Example1 expression 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 enablesData.ByteString.Builderto efficiently serialise large data structures and produce the output incrementally:Example5 expressions 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
(<>).Examples
Define a Monoid over finite bit strings under
xor. Use it to strictly compute thexorof a list of Int values.Example11 expressions :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 . toListExamples
Basic usage:
Example1 expression foldr (||) False [False, True, False]True
Example1 expression foldr (||) False []False
Example1 expression foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
Infinite structures
⚠️ 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-circuiting
(||)short-circuits on True values, so the following terminates because there is a True value finitely far from the left side:Example1 expression foldr (||) False (True : repeat False)True
But the following doesn't terminate:
Example1 expression foldr (||) False (repeat False ++ [True])* Hangs forever *
Laziness in the second argument
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):Example1 expression 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
Seqfrom thecontainerspackage.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` x1in 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 . toListExamples
The first example is a strict fold, which in practice is best performed with foldl'.
Example1 expression 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.
Example1 expression 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:
Example1 expression 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.
Examples
Basic usage:
Example1 expression foldr1 (+) [1..4]10
Example1 expression foldr1 (+) []Exception: Prelude.foldr1: empty list
Example1 expression foldr1 (+) Nothing*** Exception: foldr1: empty structure
Example1 expression foldr1 (-) [1..4]-2
Example1 expression foldr1 (&&) [True, False, True, True]False
Example1 expression foldr1 (||) [False, False, True, True]True
Example1 expression 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 . toListExamples
Basic usage:
Example1 expression foldl1 (+) [1..4]10
Example1 expression foldl1 (+) []*** Exception: Prelude.foldl1: empty list
Example1 expression foldl1 (+) Nothing*** Exception: foldl1: empty structure
Example1 expression foldl1 (-) [1..4]-8
Example1 expression foldl1 (&&) [True, False, True, True]False
Example1 expression foldl1 (||) [False, False, True, True]True
Example1 expression 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.
Examples
Basic usage:
Example1 expression toList Nothing[]
Example1 expression toList (Just 42)[42]
Example1 expression toList (Left "foo")[]
Example1 expression toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8)))[5,17,12,8]
For lists, toList is the identity:
Example1 expression 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.
Examples
Basic usage:
Example1 expression null []True
Example1 expression 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).
Example1 expression 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.
Examples
Basic usage:
Example1 expression length []0
Example2 expressions 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.
Examples
Basic usage:
Example1 expression 3 `elem` []False
Example1 expression 3 `elem` [1,2]False
Example1 expression 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:
Example1 expression 3 `elem` [1..]True
Example1 expression 3 `elem` ([4..] ++ [3])* Hangs forever *
maximum :: Ord a => t a -> aThe largest element of a non-empty structure.
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.
Examples
Basic usage:
Example1 expression maximum [1..10]10
Example1 expression maximum []*** Exception: Prelude.maximum: empty list
Example1 expression 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 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.
Examples
Basic usage:
Example1 expression minimum [1..10]1
Example1 expression minimum []*** Exception: Prelude.minimum: empty list
Example1 expression 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.
Examples
Basic usage:
Example1 expression sum []0
Example1 expression sum [42]42
Example1 expression sum [1..10]55
Example1 expression sum [4.1, 2.0, 1.7]7.8
Example1 expression sum [1..]* Hangs forever *
product :: Num a => t a -> aThe product function computes the product of the numbers of a structure.
Examples
Basic usage:
Example1 expression product []1
Example1 expression product [42]42
Example1 expression product [1..10]3628800
Example1 expression product [4.1, 2.0, 1.7]13.939999999999998
Example1 expression product [1..]* Hangs forever *
Instances34Foldable, …
Foldable NonEmptyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable IdentityDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.IdentityFoldable FirstDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable LastDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable DownDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable DualDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable ProductDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable SumDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable ZipListDefined in ghc-internal-9.1003.0 · GHC.Internal.Functor.ZipListFoldable Par1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable MaybeDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable SoloDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable []Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable ProxyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable U1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UAddrDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable UWordDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable V1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable (Array i)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable (Either a)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable (Tuple2 a)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable (Const m)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.ConstFoldable f => Foldable (Ap f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Alt f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Rec1 f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable (K1 i c)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (f :*: g)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (f :+: g)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (M1 i c f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (f :.: g)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable