HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulerelude-1.2.0.0Haskell2010

Relude.Foldable.Reexport

SPDX-License-Identifier : MIT Maintainer : Kowainik xrom.xkov@gmail.com Stability : Stable Portability : Portable

Reexports Data.Foldable and Data.Traversable.

  • 4 classes
  • 39 values
  • Packagerelude-1.2.0.0
  • Exports43
  • LanguageHaskell2010
  • LicenceMIT
  • SourceReexport.hs

Foldable reexports

20 declarations
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]
  • 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
  • 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 *
Instances70Foldable, …
  • Foldable ComplexDefined in base-4.20.2.0 · Data.Complex
  • Foldable FirstDefined in base-4.20.2.0 · Data.Semigroup
  • Foldable LastDefined in base-4.20.2.0 · Data.Semigroup
  • Foldable MaxDefined in base-4.20.2.0 · Data.Semigroup
  • Foldable MinDefined in base-4.20.2.0 · Data.Semigroup
  • Foldable SCCDefined in containers-0.7 · Data.Graph
  • Foldable IntMapDefined in containers-0.7 · Data.IntMap.Internal

    Folds in order of increasing key.

  • Foldable DigitDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable ElemDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable FingerTreeDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable NodeDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable SeqDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable ViewLDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable ViewRDefined in containers-0.7 · Data.Sequence.Internal
  • Foldable SetDefined in containers-0.7 · Data.Set.Internal

    Folds in order of increasing key.

  • Foldable TreeDefined in containers-0.7 · Data.Tree

    Folds in preorder

  • Foldable MaybeSDefined in containers-0.7 · Utils.Containers.Internal.StrictMaybe
  • Foldable NonEmptyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable IdentityDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.Identity
  • Foldable FirstDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable LastDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable DownDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable DualDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable ProductDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable SumDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable ZipListDefined in ghc-internal-9.1003.0 · GHC.Internal.Functor.ZipList
  • Foldable Par1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable MaybeDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable SoloDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable HashedDefined in hashable-1.4.7.0 · Data.Hashable.Class
  • Foldable TyVarBndrDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
  • Foldable HashSetDefined in unordered-containers-0.2.21 · Data.HashSet.Internal
  • Foldable []Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable ProxyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable U1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UAddrDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable UWordDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable V1Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable (Arg a)Defined in base-4.20.2.0 · Data.Semigroup
  • Foldable (Map k)Defined in containers-0.7 · Data.Map.Internal

    Folds in order of increasing key.

  • Foldable (Array i)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable (Either a)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable (Tuple2 a)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable (HashMap k)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
  • Foldable f => Foldable (Lift f)Defined in transformers-0.6.1.1 · Control.Applicative.Lift
  • Foldable f => Foldable (MaybeT f)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Maybe
  • Foldable m => Foldable (CatchT m)Defined in exceptions-0.10.9 · Control.Monad.Catch.Pure
  • Foldable (Const m)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.Const
  • Foldable (Constant a)Defined in transformers-0.6.1.1 · Data.Functor.Constant
  • Foldable f => Foldable (Ap f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable f => Foldable (Alt f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable f => Foldable (Rec1 f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • Foldable f => Foldable (Backwards f)Defined in transformers-0.6.1.1 · Control.Applicative.Backwards

    Derived instance.

  • Foldable f => Foldable (ExceptT e f)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Except
  • Foldable f => Foldable (IdentityT f)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Identity
  • Foldable f => Foldable (WriterT w f)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.Lazy
  • Foldable f => Foldable (WriterT w f)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Writer.Strict
  • Foldable f => Foldable (Reverse f)Defined in transformers-0.6.1.1 · Data.Functor.Reverse

    Fold from right to left.

  • Foldable (K1 i c)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • (Foldable f, Foldable g) => Foldable (Product f g)Defined in base-4.20.2.0 · Data.Functor.Product
  • (Foldable f, Foldable g) => Foldable (Sum f g)Defined in base-4.20.2.0 · Data.Functor.Sum
  • (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.Foldable
  • Foldable f => Foldable (M1 i c f)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
  • (Foldable f, Foldable g) => Foldable (Compose f g)Defined in base-4.20.2.0 · Data.Functor.Compose
  • (Foldable f, Foldable g) => Foldable (f :.: g)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Foldable
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 *
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"
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]
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
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]
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.

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.

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 *
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""!"
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.

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""!"
classclass (Functor t, Foldable t) => Traversable (t :: Type -> Type) where
#

Functors representing data structures that can be transformed to structures of the same shape by performing an Applicative (or, therefore, Monad) action on each element from left to right.

A more detailed description of what same shape means, the various methods, how traversals are constructed, and example advanced use-cases can be found in the Overview section of Data.Traversable#overview.

For the class laws see the Laws section of Data.Traversable#laws.

Methods

  • traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

    Map each element of a structure to an action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see traverse_.

    Examples

    Basic usage:

    In the first two examples we show each evaluated action mapping to the output structure.

    Example1 expression
    traverse Just [1,2,3,4]Just [1,2,3,4]
    Example1 expression
    traverse id [Right 1, Right 2, Right 3, Right 4]Right [1,2,3,4]

    In the next examples, we show that Nothing and Left values short circuit the created structure.

    Example1 expression
    traverse (const Nothing) [1,2,3,4]Nothing
    Example1 expression
    traverse (\x -> if odd x then Just x else Nothing)  [1,2,3,4]Nothing
    Example1 expression
    traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]Left 0
  • sequenceA :: Applicative f => t (f a) -> f (t a)

    Evaluate each action in the structure from left to right, and collect the results. For a version that ignores the results see sequenceA_.

    Examples

    Basic usage:

    For the first two examples we show sequenceA fully evaluating a a structure and collecting the results.

    Example1 expression
    sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
    Example1 expression
    sequenceA [Right 1, Right 2, Right 3]Right [1,2,3]

    The next two example show Nothing and Just will short circuit the resulting structure if present in the input. For more context, check the Traversable instances for Either and Maybe.

    Example1 expression
    sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
    Example1 expression
    sequenceA [Right 1, Right 2, Right 3, Left 4]Left 4
  • mapM :: Monad m => (a -> m b) -> t a -> m (t b)

    Map each element of a structure to a monadic action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see Data.Foldable.mapM_.

    Examples

    mapM is literally a traverse with a type signature restricted to Monad. Its implementation may be more efficient due to additional power of Monad.

  • sequence :: Monad m => t (m a) -> m (t a)

    Evaluate each monadic action in the structure from left to right, and collect the results. For a version that ignores the results see Data.Foldable.sequence_.

    Examples

    Basic usage:

    The first two examples are instances where the input and and output of sequence are isomorphic.

    Example1 expression
    sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
    Example1 expression
    sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]

    The following examples demonstrate short circuit behavior for sequence.

    Example1 expression
    sequence $ Left [1,2,3,4]Left [1,2,3,4]
    Example1 expression
    sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0
Instances66Traversable, …
valueforM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
#

forM is mapM with its arguments flipped. For a version that ignores the results see Data.Foldable.forM_.

valuemapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
#

The mapAccumL function behaves like a combination of fmap and foldl; it applies a function to each element of a structure, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new structure.

Examples

Basic usage:

Example1 expression
mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
Example1 expression
mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
valuemapAccumR :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
#

The mapAccumR function behaves like a combination of fmap and foldr; it applies a function to each element of a structure, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new structure.

Examples

Basic usage:

Example1 expression
mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
Example1 expression
mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])

Bi reexports

23 declarations
classclass Bifoldable (p :: Type -> Type -> Type) where
#

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:

bifold ≡ bifoldMap 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 const ≡ foldl
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)

Methods

  • bifold :: Monoid m => p m m -> m

    Combines the elements of a structure using a monoid.

    bifold ≡ bifoldMap id id
    Examples

    Basic usage:

    Example1 expression
    bifold (Right [1, 2, 3])[1,2,3]
    Example1 expression
    bifold (Left [5, 6])[5,6]
    Example1 expression
    bifold ([1, 2, 3], [4, 5])[1,2,3,4,5]
    Example1 expression
    bifold (Product 6, Product 7)Product {getProduct = 42}
    Example1 expression
    bifold (Sum 6, Sum 7)Sum {getSum = 13}
  • bifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> m

    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:

    Example1 expression
    bifoldMap (take 3) (fmap digitToInt) ([1..], "89")[1,2,3,8,9]
    Example1 expression
    bifoldMap (take 3) (fmap digitToInt) (Left [1..])[1,2,3]
    Example1 expression
    bifoldMap (take 3) (fmap digitToInt) (Right "89")[8,9]
  • bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c

    Combines the elements of a structure in a right 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:

    bifoldr f g z ≡ foldr (either f g) z . toEitherList
    Examples

    Basic usage:

    > bifoldr (+) (*) 3 (5, 7)
    26 -- 5 + (7 * 3)
    
    > bifoldr (+) (*) 3 (7, 5)
    22 -- 7 + (5 * 3)
    
    > bifoldr (+) (*) 3 (Right 5)
    15 -- 5 * 3
    
    > bifoldr (+) (*) 3 (Left 5)
    8 -- 5 + 3
    
  • bifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c

    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
    
Instances13Bifoldable, …
  • Bifoldable ArgDefined in base-4.20.2.0 · Data.Semigroup
  • Bifoldable MapDefined in containers-0.7 · Data.Map.Internal
  • Bifoldable EitherDefined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable Tuple2Defined in base-4.20.2.0 · Data.Bifoldable

    Class laws for tuples hold only up to laziness. The Bifoldable methods are lazier than their Foldable counterparts. For example the law bifoldr (flip const) ≡ foldr does not hold for tuples if laziness is exploited:

    Example2 expressions
    bifoldr (flip const) (:) [] (undefined :: (Int, Word)) `seq` ()()foldr (:) [] (undefined :: (Int, Word)) `seq` ()*** Exception: Prelude.undefined
  • Bifoldable HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
  • Bifoldable ConstDefined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable ConstantDefined in transformers-0.6.1.1 · Data.Functor.Constant
  • Bifoldable (Tuple3 x)Defined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable (K1 i)Defined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable (Tuple4 x y)Defined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable (Tuple5 x y z)Defined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable (Tuple6 x y z w)Defined in base-4.20.2.0 · Data.Bifoldable
  • Bifoldable (Tuple7 x y z w v)Defined in base-4.20.2.0 · Data.Bifoldable
valuebiList :: Bifoldable t => t a a -> [a]
#

Collects the list of elements of a structure, from left to right.

Examples

Basic usage:

Example1 expression
biList (18, 42)[18,42]
Example1 expression
biList (Left 18)[18]
valuebiall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
#

Determines whether all elements of the structure satisfy their appropriate predicate argument. Empty structures yield True.

Examples

Basic usage:

Example1 expression
biall even isDigit (27, 't')False
Example1 expression
biall even isDigit (26, '8')True
Example1 expression
biall even isDigit (Left 27)False
Example1 expression
biall even isDigit (Left 26)True
Example1 expression
biall even isDigit (BiList [26, 52] ['3', '8'])True

Empty structures yield True:

Example1 expression
biall even isDigit (BiList [] [])True
valuebiand :: Bifoldable t => t Bool Bool -> Bool
#

biand 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
biand (True, False)False
Example1 expression
biand (True, True)True
Example1 expression
biand (Left True)True

Empty structures yield True:

Example1 expression
biand (BiList [] [])True

A False value finitely far from the left end yields False (short circuit):

Example1 expression
biand (BiList [True, True, False, True] (repeat True))False

A False value infinitely far from the left end hangs:

> biand (BiList (repeat True) [False])
* Hangs forever *

An infinitely True value hangs:

> biand (BiList (repeat True) [])
* Hangs forever *
valuebiany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
#

Determines whether any element of the structure satisfies its appropriate predicate argument. Empty structures yield False.

Examples

Basic usage:

Example1 expression
biany even isDigit (27, 't')False
Example1 expression
biany even isDigit (27, '8')True
Example1 expression
biany even isDigit (26, 't')True
Example1 expression
biany even isDigit (Left 27)False
Example1 expression
biany even isDigit (Left 26)True
Example1 expression
biany even isDigit (BiList [27, 53] ['t', '8'])True

Empty structures yield False:

Example1 expression
biany even isDigit (BiList [] [])False
valuebiasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a
#

The sum of a collection of actions, generalizing biconcat.

Examples

Basic usage:

Example1 expression
biasum (Nothing, Nothing)Nothing
Example1 expression
biasum (Nothing, Just 42)Just 42
Example1 expression
biasum (Just 18, Nothing)Just 18
Example1 expression
biasum (Just 18, Just 42)Just 18
valuebielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
#

Does the element occur in the structure?

Examples

Basic usage:

Example1 expression
bielem 42 (17, 42)True
Example1 expression
bielem 42 (17, 43)False
Example1 expression
bielem 42 (Left 42)True
Example1 expression
bielem 42 (Right 13)False
Example1 expression
bielem 42 (BiList [1..5] [1..100])True
Example1 expression
bielem 42 (BiList [1..5] [1..41])False
valuebifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a
#

The bifind 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
bifind even (27, 53)Nothing
Example1 expression
bifind even (27, 52)Just 52
Example1 expression
bifind even (26, 52)Just 26

Empty structures always yield Nothing:

Example1 expression
bifind even (BiList [] [])Nothing
valuebifoldl'
  1. :: Bifoldable t
  2. => a -> b -> a
  3. -> a -> c -> a
  4. -> a
  5. -> t b c
  6. -> a
#

As bifoldl, but strict in the result of the reduction functions at each step.

This ensures that each step of the bifold 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, monolithic result (e.g., bilength).

valuebifoldlM
  1. :: (Bifoldable t, Monad m)
  2. => a -> b -> m a
  3. -> a -> c -> m a
  4. -> a
  5. -> t b c
  6. -> m a
#

Left associative monadic bifold over a structure.

Examples

Basic usage:

Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 ("Hello", True)"Hello""True"42
Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Right True)"True"42
Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Left "Hello")"Hello"42
valuebifoldr'
  1. :: Bifoldable t
  2. => a -> c -> c
  3. -> b -> c -> c
  4. -> c
  5. -> t a b
  6. -> c
#

As bifoldr, but strict in the result of the reduction functions at each step.

valuebifoldrM
  1. :: (Bifoldable t, Monad m)
  2. => a -> c -> m c
  3. -> b -> c -> m c
  4. -> c
  5. -> t a b
  6. -> m c
#

Right associative monadic bifold over a structure.

valuebifor_
  1. :: (Bifoldable t, Applicative f)
  2. => t a b
  3. -> a -> f c
  4. -> b -> f d
  5. -> f ()
#

As bitraverse_, but with the structure as the primary argument. For a version that doesn't ignore the results, see bifor.

Examples

Basic usage:

Example1 expression
bifor_ ("Hello", True) print (print . show)"Hello""True"
Example1 expression
bifor_ (Right True) print (print . show)"True"
Example1 expression
bifor_ (Left "Hello") print (print . show)"Hello"
valuebilength :: Bifoldable t => t a b -> Int
#

Returns the size/length of a finite structure as an Int.

Examples

Basic usage:

Example1 expression
bilength (True, 42)2
Example1 expression
bilength (Right 42)1
Example1 expression
bilength (BiList [1,2,3] [4,5])5
Example1 expression
bilength (BiList [] [])0

On infinite structures, this function hangs:

> bilength (BiList [1..] [])
* Hangs forever *
valuebinull :: Bifoldable t => t a b -> Bool
#

Test whether the structure is empty.

Examples

Basic usage:

Example1 expression
binull (18, 42)False
Example1 expression
binull (Right 42)False
Example1 expression
binull (BiList [] [])True
valuebior :: Bifoldable t => t Bool Bool -> Bool
#

bior 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
bior (True, False)True
Example1 expression
bior (False, False)False
Example1 expression
bior (Left True)True

Empty structures yield False:

Example1 expression
bior (BiList [] [])False

A True value finitely far from the left end yields True (short circuit):

Example1 expression
bior (BiList [False, False, True, False] (repeat False))True

A True value infinitely far from the left end hangs:

> bior (BiList (repeat False) [True])
* Hangs forever *

An infinitely False value hangs:

> bior (BiList (repeat False) [])
* Hangs forever *
valuebisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> 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 bisequence.

Examples

Basic usage:

Example1 expression
bisequence_ (print "Hello", print "World")"Hello""World"
Example1 expression
bisequence_ (Left (print "Hello"))"Hello"
Example1 expression
bisequence_ (Right (print "World"))"World"
valuebitraverse_
  1. :: (Bifoldable t, Applicative f)
  2. => a -> f c
  3. -> b -> f d
  4. -> t a b
  5. -> f ()
#

Map each element of a structure using one of two actions, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results, see bitraverse.

Examples

Basic usage:

Example1 expression
bitraverse_ print (print . show) ("Hello", True)"Hello""True"
Example1 expression
bitraverse_ print (print . show) (Right True)"True"
Example1 expression
bitraverse_ print (print . show) (Left "Hello")"Hello"
classclass (Bifunctor t, Bifoldable t) => Bitraversable (t :: Type -> Type -> Type) where
#

Bitraversable identifies bifunctorial data structures whose elements can be traversed in order, performing Applicative or Monad actions at each element, and collecting a result structure with the same shape.

As opposed to Traversable data structures, which have one variety of element on which an action can be performed, Bitraversable data structures have two such varieties of elements.

A definition of bitraverse must satisfy the following laws:

Naturality

bitraverse (t . f) (t . g) ≡ t . bitraverse f g

for every applicative transformation

t

Identity

bitraverse Identity Identity ≡ Identity

Composition

Compose . fmap (bitraverse g1 g2) . bitraverse f1 f2 ≡ bitraverse (Compose . fmap g1 . f1) (Compose . fmap g2 . f2)

where an applicative transformation is a function

t :: (Applicative f, Applicative g) => f a -> g a

preserving the Applicative operations:

t (pure x) ≡ pure x
t (f <*> x) ≡ t f <*> t x

and the identity functor Identity and composition functors Compose are from Data.Functor.Identity and Data.Functor.Compose.

Some simple examples are Either and (,):

instance Bitraversable Either where
  bitraverse f _ (Left x) = Left <$> f x
  bitraverse _ g (Right y) = Right <$> g y

instance Bitraversable (,) where
  bitraverse f g (x, y) = (,) <$> f x <*> g y

Bitraversable relates to its superclasses in the following ways:

bimap f g ≡ runIdentity . bitraverse (Identity . f) (Identity . g)
bifoldMap f g ≡ getConst . bitraverse (Const . f) (Const . g)

These are available as bimapDefault and bifoldMapDefault respectively.

If the type is also an instance of Traversable, then it must satisfy (up to laziness):

traverse ≡ bitraverse pure

Methods

  • bitraverse :: Applicative f => (a -> f c) -> (b -> f d) -> t a b -> f (t c d)

    Evaluates the relevant functions at each element in the structure, running the action, and builds a new structure with the same shape, using the results produced from sequencing the actions.

    bitraverse f g ≡ bisequenceA . bimap f g

    For a version that ignores the results, see bitraverse_.

    Examples

    Basic usage:

    Example1 expression
    bitraverse listToMaybe (find odd) (Left [])Nothing
    Example1 expression
    bitraverse listToMaybe (find odd) (Left [1, 2, 3])Just (Left 1)
    Example1 expression
    bitraverse listToMaybe (find odd) (Right [4, 5])Just (Right 5)
    Example1 expression
    bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])Just (1,5)
    Example1 expression
    bitraverse listToMaybe (find odd) ([], [4, 5])Nothing
Instances11Bitraversable, …
  • Bitraversable ArgDefined in base-4.20.2.0 · Data.Semigroup
  • Bitraversable EitherDefined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable Tuple2Defined in base-4.20.2.0 · Data.Bitraversable

    Class laws for tuples hold only up to laziness. The Bitraversable methods are lazier than their Traversable counterparts. For example the law bitraverse pure ≡ traverse does not hold for tuples if laziness is exploited:

    Example2 expressions
    (bitraverse pure pure undefined :: IO (Int, Word)) `seq` ()()(traverse pure undefined :: IO (Int, Word)) `seq` ()*** Exception: Prelude.undefined
  • Bitraversable ConstDefined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable ConstantDefined in transformers-0.6.1.1 · Data.Functor.Constant
  • Bitraversable (Tuple3 x)Defined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable (K1 i)Defined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable (Tuple4 x y)Defined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable (Tuple5 x y z)Defined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable (Tuple6 x y z w)Defined in base-4.20.2.0 · Data.Bitraversable
  • Bitraversable (Tuple7 x y z w v)Defined in base-4.20.2.0 · Data.Bitraversable
valuebifor
  1. :: (Bitraversable t, Applicative f)
  2. => t a b
  3. -> a -> f c
  4. -> b -> f d
  5. -> f (t c d)
#

bifor is bitraverse with the structure as the first argument. For a version that ignores the results, see bifor_.

Examples

Basic usage:

Example1 expression
bifor (Left []) listToMaybe (find even)Nothing
Example1 expression
bifor (Left [1, 2, 3]) listToMaybe (find even)Just (Left 1)
Example1 expression
bifor (Right [4, 5]) listToMaybe (find even)Just (Right 4)
Example1 expression
bifor ([1, 2, 3], [4, 5]) listToMaybe (find even)Just (1,4)
Example1 expression
bifor ([], [4, 5]) listToMaybe (find even)Nothing
valuebisequence :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b)
#

Sequences all the actions in a structure, building a new structure with the same shape using the results of the actions. For a version that ignores the results, see bisequence_.

bisequence ≡ bitraverse id id
Examples

Basic usage:

Example1 expression
bisequence (Just 4, Nothing)Nothing
Example1 expression
bisequence (Just 4, Just 5)Just (4,5)
Example1 expression
bisequence ([1, 2, 3], [4, 5])[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]