fold package:relude

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:
>>> 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
Fixes and additions to Foldable. Specifically:
A left-associative fold that's tail-recursive but can still short-circuit. Returning a Left short-circuits and immediately returns the value inside. Returning a Right continues the fold as usual with the value inside.
>>> foldlSC (\acc x -> if x == 0 then Left 0 else Right $! acc * x) 1 [1..6]
720

>>> foldlSC (\acc x -> if x == 0 then Left 0 else Right $! acc * x) 1 (0:error "Short-circuiting should keep this from happening")
0
Combine the elements of a non-empty structure using a semigroup.
>>> fold1 (1 :| [2, 3, 4 :: SG.Sum Int])
Sum {getSum = 10}

>>> fold1 (4 :| [5, 10 :: SG.Product Int])
Product {getProduct = 200}
Map each element of the non-empty structure to a semigroup, and combine the results.
>>> foldMap1 SG.Sum (1 :| [2, 3, 4])
Sum {getSum = 10}

>>> foldMap1 show (123 :| [456, 789, 0])
"1234567890"
Strictly folds non-empty structure with given function f:
foldl1' f [x0, x1, x2 ...] = f (f x0 x1) x2 ...
>>> foldl1' (++) ([1,2] :| [[3,4], [5,6]])
[1,2,3,4,5,6]
Combines the elements of a non-empty structure using a binary function f.
>>> foldr1 (+) 0 (1 :| [2, 3])
6

>>> foldr1 (+) 1 $ Identity 3
4
Polymorphic version of the concatMapA function.
>>> foldMapA @[Int] (Just . replicate 3) [1..3]
Just [1,1,1,2,2,2,3,3,3]
Polymorphic version of the concatMapM function.
>>> foldMapM @[Int] (Just . replicate 3) [1..3]
Just [1,1,1,2,2,2,3,3,3]
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:
>>> 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 L

>>> import qualified Data.ByteString.Builder as B

>>> let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20

>>> let 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"
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.
>>> :set -XGeneralizedNewtypeDeriving

>>> import 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 zeroBits

>>> 

>>> let bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411]

>>> (\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits
"0x42"
@since base-4.13.0.0
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
@since base-4.6.0.0
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:
>>> let f a e = do { print e ; return $ e : a }

>>> foldlM f [] [0..3]
0
1
2
3
[3,2,1,0]
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:
>>> foldr (||) False [False, True, False]
True
>>> foldr (||) False []
False
>>> 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:
>>> foldr (||) False (True : repeat False)
True
But the following doesn't terminate:
>>> 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):
>>> take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)
[1,4,7,10,13]
Contains utility functions for working with tuples.
Foldable1 is a typeclass like Foldable but for non-empty structures. For example, NonEmpty, Identity. Foldable1 has all type-safe and total methods like head1, maximum1 in contradiction with Foldable.
The class of foldable data structures that cannot be empty.
This module provides Foldable and Traversable related types and functions.
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.
Similar to foldl' but takes a function with its arguments flipped.
>>> flipfoldl' (/) 5 [2,3] :: Rational
15 % 2
This function can be useful for constructing containers from lists.
Bifoldable identifies foldable structures with two different varieties of elements (as opposed to Foldable, which has one variety of element). Common examples are Either and (,):
instance Bifoldable Either where
bifoldMap f _ (Left  a) = f a
bifoldMap _ g (Right b) = g b

instance Bifoldable (,) where
bifoldr f g z (a, b) = f a (g b z)
Some examples below also use the following BiList to showcase empty Bifoldable behaviors when relevant (Either and (,) containing always exactly resp. 1 and 2 elements):
data BiList a b = BiList [a] [b]

instance Bifoldable BiList where
bifoldr f g z (BiList as bs) = foldr f (foldr g z bs) as
A minimal Bifoldable definition consists of either bifoldMap or bifoldr. When defining more than this minimal set, one should ensure that the following identities hold:
bifoldbifoldMap id id
bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty
bifoldr f g z t ≡ appEndo (bifoldMap (Endo . f) (Endo . g) t) z
If the type is also an instance of Foldable, then it must satisfy (up to laziness):
bifoldl constfoldl
bifoldr (flip const) ≡ foldr
bifoldMap (const mempty) ≡ foldMap
If the type is also a Bifunctor instance, it should satisfy:
bifoldMap f g ≡ bifold . bimap f g
which implies that
bifoldMap f g . bimap h i ≡ bifoldMap (f . h) (g . i)
Combines the elements of a structure using a monoid.
bifoldbifoldMap id id

Examples

Basic usage:
>>> bifold (Right [1, 2, 3])
[1,2,3]
>>> bifold (Left [5, 6])
[5,6]
>>> bifold ([1, 2, 3], [4, 5])
[1,2,3,4,5]
>>> bifold (Product 6, Product 7)
Product {getProduct = 42}
>>> bifold (Sum 6, Sum 7)
Sum {getSum = 13}
Combines the elements of a structure, given ways of mapping them to a common monoid.
bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty

Examples

Basic usage:
>>> bifoldMap (take 3) (fmap digitToInt) ([1..], "89")
[1,2,3,8,9]
>>> bifoldMap (take 3) (fmap digitToInt) (Left [1..])
[1,2,3]
>>> bifoldMap (take 3) (fmap digitToInt) (Right "89")
[8,9]
A default definition of bifoldMap in terms of the Bitraversable operations.
bifoldMapDefault f g ≡
getConst . bitraverse (Const . f) (Const . g)
Combines the elements of a structure in a left associative manner. Given a hypothetical function toEitherList :: p a b -> [Either a b] yielding a list of all elements of a structure in order, the following would hold:
bifoldl f g z
≡ foldl (acc -> either (f acc) (g acc)) z . toEitherList
Note that if you want an efficient left-fold, you probably want to use bifoldl' instead of bifoldl. The reason is that the latter does not force the "inner" results, resulting in a thunk chain which then must be evaluated from the outside-in.

Examples

Basic usage:
> bifoldl (+) (*) 3 (5, 7)
56 -- (5 + 3) * 7

> bifoldl (+) (*) 3 (7, 5)
50 -- (7 + 3) * 5

> bifoldl (+) (*) 3 (Right 5)
15 -- 5 * 3

> bifoldl (+) (*) 3 (Left 5)
8 -- 5 + 3