HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleextra-1.8Haskell2010

Data.Foldable.Extra

  • 1 class
  • 32 values
  • Packageextra-1.8
  • Exports33
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceFoldable.hs
classclass Foldable (t :: Type -> Type) where
#

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 Foldable

A 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 -> m

    Given 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 -> m

    Map 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 enables Data.ByteString.Builder to 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 -> m

    A 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 the xor of 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 -> b

    Right-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 . toList
    Examples

    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 -> b

    foldr' 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 -> b

    Left-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` xn

    Note 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 . toList
    Examples

    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 -> b

    Left-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 . toList
  • foldr1 :: (a -> a -> a) -> t a -> a

    A 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 -> a

    A 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 . toList
    Examples

    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 -> Bool

    Test 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 -> Int

    Returns 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 4

    Does 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 -> a

    The 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 -> a

    The 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 -> a

    The 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 -> a

    The 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 *
Instances54Foldable, …
valueall :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether all elements of the structure satisfy the predicate.

Examples

Basic usage:

Example1 expression
all (> 3) []True
Example1 expression
all (> 3) [1,2]False
Example1 expression
all (> 3) [1,2,3,4,5]False
Example1 expression
all (> 3) [1..]False
Example1 expression
all (> 3) [4..]* Hangs forever *
valueand :: Foldable t => t Bool -> Bool
#

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.

Examples

Basic usage:

Example1 expression
and []True
Example1 expression
and [True]True
Example1 expression
and [False]False
Example1 expression
and [True, True, False]False
Example1 expression
and (False : repeat True) -- Infinite list [False,True,True,True,...False
Example1 expression
and (repeat True)* Hangs forever *
valueany :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether any element of the structure satisfies the predicate.

Examples

Basic usage:

Example1 expression
any (> 3) []False
Example1 expression
any (> 3) [1,2]False
Example1 expression
any (> 3) [1,2,3,4,5]True
Example1 expression
any (> 3) [1..]True
Example1 expression
any (> 3) [0, -1..]* Hangs forever *
valueconcat :: Foldable t => t [a] -> [a]
#

The concatenation of all the elements of a container of lists.

Examples

Basic usage:

Example1 expression
concat (Just [1, 2, 3])[1,2,3]
Example1 expression
concat (Left 42)[]
Example1 expression
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
valueconcatMap :: Foldable t => (a -> [b]) -> t a -> [b]
#

Map a function over all the elements of a container and concatenate the resulting lists.

Examples

Basic usage:

Example1 expression
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
Example1 expression
concatMap (take 3) (Just [1..])[1,2,3]
valuemapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
#

Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see Data.Traversable.mapM.

mapM_ is just like traverse_, but specialised to monadic actions.

valuenotElem :: (Foldable t, Eq a) => a -> t a -> Bool
#

notElem is the negation of elem.

Examples

Basic usage:

Example1 expression
3 `notElem` []True
Example1 expression
3 `notElem` [1,2]True
Example1 expression
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:

Example1 expression
3 `notElem` [1..]False
Example1 expression
3 `notElem` ([4..] ++ [3])* Hangs forever *
valueor :: Foldable t => t Bool -> Bool
#

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.

Examples

Basic usage:

Example1 expression
or []False
Example1 expression
or [True]True
Example1 expression
or [False]False
Example1 expression
or [True, True, False]True
Example1 expression
or (True : repeat False) -- Infinite list [True,False,False,False,...True
Example1 expression
or (repeat False)* Hangs forever *
valuesequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
#

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.

valuefind :: Foldable t => (a -> Bool) -> t a -> Maybe a
#

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

Examples

Basic usage:

Example1 expression
find (> 42) [0, 5..]Just 45
Example1 expression
find (> 12) [1..7]Nothing
valuemaximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

The largest element of a non-empty structure with respect to the given comparison function.

Examples

Basic usage:

Example1 expression
maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"Longest"

WARNING: This function is partial for possibly-empty structures like lists.

valueminimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

The least element of a non-empty structure with respect to the given comparison function.

Examples

Basic usage:

Example1 expression
minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"!"

WARNING: This function is partial for possibly-empty structures like lists.

valueasum :: (Foldable t, Alternative f) => t (f a) -> f a
#

The sum of a collection of actions using (<|>), generalizing concat.

asum is just like msum, but generalised to Alternative.

Examples

Basic usage:

Example1 expression
asum [Just "Hello", Nothing, Just "World"]Just "Hello"
valuefoldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
#

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 empty

For 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 >>= f2

Another 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 $ z

The 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` y
Examples

Basic usage:

Example2 expressions
let f a e = do { print e ; return $ e : a }foldlM f [] [0..3]0123[3,2,1,0]
valuefoldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
#

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 empty

For 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 >>= f2

Another 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 $ z

The 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))))).
Examples

Basic usage:

Example2 expressions
let f i acc = do { print i ; return $ i : acc }foldrM f [] [0..3]3210[0,1,2,3]
valueforM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
#

forM_ is mapM_ with its arguments flipped. For a version that doesn't ignore the results see Data.Traversable.forM.

forM_ is just like for_, but specialised to monadic actions.

valuemsum :: (Foldable t, MonadPlus m) => t (m a) -> m a
#

The sum of a collection of actions using (<|>), generalizing concat.

msum is just like asum, but specialised to MonadPlus.

Examples

Basic usage, using the MonadPlus instance for Maybe:

Example1 expression
msum [Just "Hello", Nothing, Just "World"]Just "Hello"
valuesequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
#

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.

Examples

Basic usage:

Example1 expression
sequenceA_ [print "Hello", print "world", print "!"]"Hello""world""!"
valuetraverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
#

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.

Examples

Basic usage:

Example1 expression
traverse_ print ["Hello", "world", "!"]"Hello""world""!"
valuecompareLength :: Foldable f => f a -> Int -> Ordering
#

Lazily compare the length of a Foldable with a number.

compareLength [1,2,3] 1 == GT
compareLength [1,2] 2 == EQ
\(xs :: [Int]) n -> compareLength xs n == compare (length xs) n
compareLength (1:2:3:undefined) 2 == GT