Determines whether all elements of the structure satisfy the predicate.
Examples
Basic usage:
all (> 3) []True
all (> 3) [1,2]False
all (> 3) [1,2,3,4,5]False
all (> 3) [1..]False
all (> 3) [4..]* Hangs forever *
:: a typeCtrl KGHC 9.14.1 · lts/ghc-9.14.x · 45dd537 · 2026-10-11
Modulerelude-1.2.2.2Haskell2010
SPDX-License-Identifier : MIT Maintainer : Kowainik xrom.xkov@gmail.com Stability : Stable Portability : Portable
Reexports Data.Foldable and Data.Traversable.
Foldable reexportsDetermines whether all elements of the structure satisfy the predicate.
Basic usage:
all (> 3) []True
all (> 3) [1,2]False
all (> 3) [1,2,3,4,5]False
all (> 3) [1..]False
all (> 3) [4..]* Hangs forever *
and returns the conjunction of a container of Bools. For the result to be True, the container must be finite; False, however, results from a False value finitely far from the left end.
Basic usage:
and []True
and [True]True
and [False]False
and [True, True, False]False
and (False : repeat True) -- Infinite list [False,True,True,True,...False
and (repeat True)* Hangs forever *
Determines whether any element of the structure satisfies the predicate.
Basic usage:
any (> 3) []False
any (> 3) [1,2]False
any (> 3) [1,2,3,4,5]True
any (> 3) [1..]True
any (> 3) [0, -1..]* Hangs forever *
The sum of a collection of actions using (<|>), generalizing concat.
asum is just like msum, but generalised to Alternative.
Basic usage:
asum [Just "Hello", Nothing, Just "World"]Just "Hello"
The concatenation of all the elements of a container of lists.
Basic usage:
concat (Just [1, 2, 3])[1,2,3]
concat (Left 42)[]
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
Map a function over all the elements of a container and concatenate the resulting lists.
Basic usage:
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
concatMap (take 3) (Just [1..])[1,2,3]
Left-to-right monadic fold over the elements of a structure.
Given a structure t with elements (a, b, ..., w, x, y), the result of
a fold with an operator function f is equivalent to:
foldlM f z t = do
aa <- f z a
bb <- f aa b
...
xx <- f ww x
yy <- f xx y
return yy -- Just @return z@ when the structure is emptyFor a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2Another way of thinking about foldlM is that it amounts to an application
to z of a Kleisli composition:
foldlM f z t =
flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ zThe monadic effects of foldlM are sequenced from left to right.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from an initial
segment of the element sequence. If you want to evaluate the monadic
effects in right-to-left order, or perhaps be able to short-circuit after
processing a tail of the sequence of elements, you'll need to use foldrM
instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the rightmost element y, so that, ignoring effects, the result
looks like a left fold:
((((z `f` a) `f` b) ... `f` w) `f` x) `f` yBasic usage:
let f a e = do { print e ; return $ e : a }foldlM f [] [0..3]0123[3,2,1,0]
for_ is traverse_ with its arguments flipped. For a version that doesn't ignore the results see for. This is forM_ generalised to Applicative actions.
for_ is just like forM_, but generalised to Applicative actions.
Basic usage:
for_ [1..4] print1234
or returns the disjunction of a container of Bools. For the result to be False, the container must be finite; True, however, results from a True value finitely far from the left end.
Basic usage:
or []False
or [True]True
or [False]False
or [True, True, False]True
or (True : repeat False) -- Infinite list [True,False,False,False,...True
or (repeat False)* Hangs forever *
Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see sequenceA.
sequenceA_ is just like sequence_, but generalised to Applicative actions.
Basic usage:
sequenceA_ [print "Hello", print "world", print "!"]"Hello""world""!"
Evaluate each monadic action in the structure from left to right,
and ignore the results. For a version that doesn't ignore the
results see Data.Traversable.sequence.
sequence_ is just like sequenceA_, but specialised to monadic actions.
Map each element of a structure to an Applicative action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see traverse.
traverse_ is just like mapM_, but generalised to Applicative actions.
Basic usage:
traverse_ print ["Hello", "world", "!"]"Hello""world""!"
The Foldable class represents data structures that can be reduced to a summary value one element at a time. Strict left-associative folds are a good fit for space-efficient reduction, while lazy right-associative folds are a good fit for corecursive iteration, or for folds that short-circuit after processing an initial subsequence of the structure's elements.
Instances can be derived automatically by enabling the DeriveFoldable
extension. For example, a derived instance for a binary tree might be:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving FoldableA more detailed description can be found in the Overview section of
Data.Foldable#overview.
For the class laws see the Laws section of Data.Foldable#laws.
fold :: Monoid m => t m -> mGiven a structure with elements whose type is a Monoid, combine them
via the monoid's (<>) operator. This fold is right-associative and
lazy in the accumulator. When you need a strict left-associative fold,
use foldMap' instead, with id as the map.
Basic usage:
fold [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))Sum {getSum = 9}
Folds of unbounded structures do not terminate when the monoid's
(<>) operator is strict:
fold (repeat Nothing)* Hangs forever *
Lazy corecursive folds of unbounded structures are fine:
take 12 $ fold $ map (\i -> [i..i+2]) [0..][0,1,2,1,2,3,2,3,4,3,4,5]sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..]2666668666666
foldMap :: Monoid m => (a -> m) -> t a -> mMap each element of the structure into a monoid, and combine the
results with (<>). This fold is right-associative and lazy in the
accumulator. For strict left-associative folds consider foldMap'
instead.
Basic usage:
foldMap Sum [1, 3, 5]Sum {getSum = 9}
foldMap Product [1, 3, 5]Product {getProduct = 15}
foldMap (replicate 3) [1, 2, 3][1,1,1,2,2,2,3,3,3]
When a Monoid's (<>) is lazy in its second argument, foldMap can
return a result even from an unbounded structure. For example, lazy
accumulation enables Data.ByteString.Builder to efficiently serialise
large data structures and produce the output incrementally:
import qualified Data.ByteString.Lazy as Limport qualified Data.ByteString.Builder as Blet bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20let lbs = B.toLazyByteString $ foldMap bld [0..]L.take 64 lbs"0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24"
foldMap' :: Monoid m => (a -> m) -> t a -> mA left-associative variant of foldMap that is strict in the
accumulator. Use this method for strict reduction when partial
results are merged via (<>).
Define a Monoid over finite bit strings under xor. Use it to
strictly compute the xor of a list of Int values.
:set -XGeneralizedNewtypeDerivingimport Data.Bits (Bits, FiniteBits, xor, zeroBits)import Data.Foldable (foldMap')import Numeric (showHex)newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits)instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b)instance Bits a => Monoid (X a) where mempty = X zeroBitslet bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411](\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits"0x42"
foldr :: (a -> b -> b) -> b -> t a -> bRight-associative fold of a structure, lazy in the accumulator.
In the case of lists, foldr, when applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)Note that since the head of the resulting expression is produced by an application of the operator to the first element of the list, given an operator lazy in its right argument, foldr can produce a terminating expression from an unbounded list.
For a general Foldable structure this should be semantically identical to,
foldr f z = foldr f z . toListBasic usage:
foldr (||) False [False, True, False]True
foldr (||) False []False
foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
⚠️ Applying foldr to infinite structures usually doesn't terminate.
It may still terminate under one of the following conditions:
the folding function is short-circuiting
the folding function is lazy on its second argument
(||) short-circuits on True values, so the following terminates
because there is a True value finitely far from the left side:
foldr (||) False (True : repeat False)True
But the following doesn't terminate:
foldr (||) False (repeat False ++ [True])* Hangs forever *
Applying foldr to infinite structures terminates when the operator is
lazy in its second argument (the initial accumulator is never used in
this case, and so could be left undefined, but [] is more clear):
take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
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 . toListtoList :: t a -> [a]List of elements of a structure, from left to right. If the entire list is intended to be reduced via a fold, just fold the structure directly bypassing the list.
Basic usage:
toList Nothing[]
toList (Just 42)[42]
toList (Left "foo")[]
toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8)))[5,17,12,8]
For lists, toList is the identity:
toList [1, 2, 3][1,2,3]
null :: t a -> BoolTest whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.
Basic usage:
null []True
null [1]False
null is expected to terminate even for infinite structures. The default implementation terminates provided the structure is bounded on the left (there is a leftmost element).
null [1..]False
length :: t a -> IntReturns the size/length of a finite structure as an Int. The default implementation just counts elements starting with the leftmost. Instances for structures that can compute the element count faster than via element-by-element counting, should provide a specialised implementation.
Basic usage:
length []0
length ['a', 'b', 'c']3length [1..]* Hangs forever *
Foldable ComplexDefined in base-4.22.0.0 · Data.ComplexFoldable FirstDefined in base-4.22.0.0 · Data.SemigroupFoldable LastDefined in base-4.22.0.0 · Data.SemigroupFoldable MaxDefined in base-4.22.0.0 · Data.SemigroupFoldable MinDefined in base-4.22.0.0 · Data.SemigroupFoldable SCCDefined in containers-0.8 · Data.GraphFoldable IntMapDefined in containers-0.8 · Data.IntMap.InternalFolds in order of increasing key.
Foldable DigitDefined in containers-0.8 · Data.Sequence.InternalFoldable ElemDefined in containers-0.8 · Data.Sequence.InternalFoldable FingerTreeDefined in containers-0.8 · Data.Sequence.InternalFoldable NodeDefined in containers-0.8 · Data.Sequence.InternalFoldable SeqDefined in containers-0.8 · Data.Sequence.InternalFoldable ViewLDefined in containers-0.8 · Data.Sequence.InternalFoldable ViewRDefined in containers-0.8 · Data.Sequence.InternalFoldable SetDefined in containers-0.8 · Data.Set.InternalFolds in order of increasing key.
Foldable PostOrderDefined in containers-0.8 · Data.TreeFoldable TreeDefined in containers-0.8 · Data.TreeFolds in pre-order.
Foldable MaybeSDefined in containers-0.8 · Utils.Containers.Internal.StrictMaybeFoldable NonEmptyDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable IdentityDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.Functor.IdentityFoldable FirstDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable LastDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable DownDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable DualDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable ProductDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable SumDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable ZipListDefined in ghc-internal-9.1401.0 · GHC.Internal.Functor.ZipListFoldable Par1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable GenClosureDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresFoldable GenStackFieldDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresFoldable GenStackFrameDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresFoldable GenStgStackClosureDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresFoldable MaybeDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable TyVarBndrDefined in ghc-internal-9.1401.0 · GHC.Internal.TH.SyntaxFoldable SoloDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable HashedDefined in hashable-1.5.1.0 · Data.Hashable.ClassFoldable HashSetDefined in unordered-containers-0.2.21 · Data.HashSet.InternalFoldable []Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable ProxyDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable U1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UAddrDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UCharDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UDoubleDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UFloatDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UIntDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable UWordDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable V1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable (Arg a)Defined in base-4.22.0.0 · Data.SemigroupFoldable (Map k)Defined in containers-0.8 · Data.Map.InternalFolds in order of increasing key.
Foldable (Array i)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable (Either a)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable (Tuple2 a)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable (HashMap k)Defined in unordered-containers-0.2.21 · Data.HashMap.InternalFoldable f => Foldable (Lift f)Defined in transformers-0.6.1.2 · Control.Applicative.LiftFoldable f => Foldable (MaybeT f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.MaybeFoldable m => Foldable (CatchT m)Defined in exceptions-0.10.11 · Control.Monad.Catch.PureFoldable (Const m)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Functor.ConstFoldable (Constant a)Defined in transformers-0.6.1.2 · Data.Functor.ConstantFoldable f => Foldable (Ap f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Alt f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Rec1 f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (Backwards f)Defined in transformers-0.6.1.2 · Control.Applicative.BackwardsDerived instance.
Foldable f => Foldable (ExceptT e f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.ExceptFoldable f => Foldable (IdentityT f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.IdentityFoldable f => Foldable (WriterT w f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.Writer.LazyFoldable f => Foldable (WriterT w f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.Writer.StrictFoldable f => Foldable (Reverse f)Defined in transformers-0.6.1.2 · Data.Functor.ReverseFold from right to left.
Foldable (K1 i c)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (Product f g)Defined in base-4.22.0.0 · Data.Functor.Product(Foldable f, Foldable g) => Foldable (Sum f g)Defined in base-4.22.0.0 · Data.Functor.Sum(Foldable f, Foldable g) => Foldable (f :*: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (f :+: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableFoldable f => Foldable (M1 i c f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Foldable(Foldable f, Foldable g) => Foldable (Compose f g)Defined in base-4.22.0.0 · Data.Functor.Compose(Foldable f, Foldable g) => Foldable (f :.: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.FoldableThe 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.
Basic usage:
mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
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.
Basic usage:
mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
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.
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_.
Basic usage:
In the first two examples we show each evaluated action mapping to the output structure.
traverse Just [1,2,3,4]Just [1,2,3,4]
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.
traverse (const Nothing) [1,2,3,4]Nothing
traverse (\x -> if odd x then Just x else Nothing) [1,2,3,4]Nothing
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_.
Basic usage:
For the first two examples we show sequenceA fully evaluating a a structure and collecting the results.
sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
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.
sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
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_.
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_.
Basic usage:
The first two examples are instances where the input and and output of sequence are isomorphic.
sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]
The following examples demonstrate short circuit behavior for sequence.
sequence $ Left [1,2,3,4]Left [1,2,3,4]
sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0
Traversable ComplexDefined in base-4.22.0.0 · Data.ComplexTraversable FirstDefined in base-4.22.0.0 · Data.SemigroupTraversable LastDefined in base-4.22.0.0 · Data.SemigroupTraversable MaxDefined in base-4.22.0.0 · Data.SemigroupTraversable MinDefined in base-4.22.0.0 · Data.SemigroupTraversable SCCDefined in containers-0.8 · Data.GraphTraversable IntMapDefined in containers-0.8 · Data.IntMap.InternalTraverses in order of increasing key.
Traversable DigitDefined in containers-0.8 · Data.Sequence.InternalTraversable ElemDefined in containers-0.8 · Data.Sequence.InternalTraversable FingerTreeDefined in containers-0.8 · Data.Sequence.InternalTraversable NodeDefined in containers-0.8 · Data.Sequence.InternalTraversable SeqDefined in containers-0.8 · Data.Sequence.InternalTraversable ViewLDefined in containers-0.8 · Data.Sequence.InternalTraversable ViewRDefined in containers-0.8 · Data.Sequence.InternalTraversable PostOrderDefined in containers-0.8 · Data.TreeTraversable TreeDefined in containers-0.8 · Data.TreeTraverses in pre-order.
Traversable NonEmptyDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable IdentityDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable FirstDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable LastDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable DownDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable DualDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable ProductDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable SumDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable ZipListDefined in ghc-internal-9.1401.0 · GHC.Internal.Functor.ZipListTraversable Par1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable GenClosureDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresTraversable GenStackFieldDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresTraversable GenStackFrameDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresTraversable GenStgStackClosureDefined in ghc-internal-9.1401.0 · GHC.Internal.Heap.ClosuresTraversable MaybeDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable TyVarBndrDefined in ghc-internal-9.1401.0 · GHC.Internal.TH.SyntaxTraversable SoloDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable []Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable ProxyDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable U1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UAddrDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UCharDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UDoubleDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UFloatDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UIntDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable UWordDefined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable V1Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable (Arg a)Defined in base-4.22.0.0 · Data.SemigroupTraversable (Map k)Defined in containers-0.8 · Data.Map.InternalTraverses in order of increasing key.
Traversable (Either a)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable (Tuple2 a)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable (HashMap k)Defined in unordered-containers-0.2.21 · Data.HashMap.InternalTraversable f => Traversable (Lift f)Defined in transformers-0.6.1.2 · Control.Applicative.LiftTraversable f => Traversable (MaybeT f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.MaybeIx i => Traversable (Array i)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Traversable(Monad m, Traversable m) => Traversable (CatchT m)Defined in exceptions-0.10.11 · Control.Monad.Catch.PureTraversable (Const m)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable (Constant a)Defined in transformers-0.6.1.2 · Data.Functor.ConstantTraversable f => Traversable (Ap f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable f => Traversable (Alt f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable f => Traversable (Rec1 f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable f => Traversable (Backwards f)Defined in transformers-0.6.1.2 · Control.Applicative.BackwardsDerived instance.
Traversable f => Traversable (ExceptT e f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.ExceptTraversable f => Traversable (IdentityT f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.IdentityTraversable f => Traversable (WriterT w f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.Writer.LazyTraversable f => Traversable (WriterT w f)Defined in transformers-0.6.1.2 · Control.Monad.Trans.Writer.StrictTraversable f => Traversable (Reverse f)Defined in transformers-0.6.1.2 · Data.Functor.ReverseTraverse from right to left.
Traversable (K1 i c)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Traversable(Traversable f, Traversable g) => Traversable (Product f g)Defined in base-4.22.0.0 · Data.Functor.Product(Traversable f, Traversable g) => Traversable (Sum f g)Defined in base-4.22.0.0 · Data.Functor.Sum(Traversable f, Traversable g) => Traversable (f :*: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Traversable(Traversable f, Traversable g) => Traversable (f :+: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableTraversable f => Traversable (M1 i c f)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Traversable(Traversable f, Traversable g) => Traversable (Compose f g)Defined in base-4.22.0.0 · Data.Functor.Compose(Traversable f, Traversable g) => Traversable (f :.: g)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.TraversableBi reexportsCollects the list of elements of a structure, from left to right.
Basic usage:
biList (18, 42)[18,42]
biList (Left 18)[18]
Determines whether all elements of the structure satisfy their appropriate predicate argument. Empty structures yield True.
Basic usage:
biall even isDigit (27, 't')False
biall even isDigit (26, '8')True
biall even isDigit (Left 27)False
biall even isDigit (Left 26)True
biall even isDigit (BiList [26, 52] ['3', '8'])True
Empty structures yield True:
biall even isDigit (BiList [] [])True
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.
Basic usage:
biand (True, False)False
biand (True, True)True
biand (Left True)True
Empty structures yield True:
biand (BiList [] [])True
A False value finitely far from the left end yields False (short circuit):
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 *
Determines whether any element of the structure satisfies its appropriate predicate argument. Empty structures yield False.
Basic usage:
biany even isDigit (27, 't')False
biany even isDigit (27, '8')True
biany even isDigit (26, 't')True
biany even isDigit (Left 27)False
biany even isDigit (Left 26)True
biany even isDigit (BiList [27, 53] ['t', '8'])True
Empty structures yield False:
biany even isDigit (BiList [] [])False
The sum of a collection of actions, generalizing biconcat.
Basic usage:
biasum (Nothing, Nothing)Nothing
biasum (Nothing, Just 42)Just 42
biasum (Just 18, Nothing)Just 18
biasum (Just 18, Just 42)Just 18
Does the element occur in the structure?
Basic usage:
bielem 42 (17, 42)True
bielem 42 (17, 43)False
bielem 42 (Left 42)True
bielem 42 (Right 13)False
bielem 42 (BiList [1..5] [1..100])True
bielem 42 (BiList [1..5] [1..41])False
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.
Basic usage:
bifind even (27, 53)Nothing
bifind even (27, 52)Just 52
bifind even (26, 52)Just 26
Empty structures always yield Nothing:
bifind even (BiList [] [])Nothing
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).
Left associative monadic bifold over a structure.
Basic usage:
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 ("Hello", True)"Hello""True"42
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Right True)"True"42
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Left "Hello")"Hello"42
As bifoldr, but strict in the result of the reduction functions at each step.
Right associative monadic bifold over a structure.
As bitraverse_, but with the structure as the primary argument. For a version that doesn't ignore the results, see bifor.
Basic usage:
bifor_ ("Hello", True) print (print . show)"Hello""True"
bifor_ (Right True) print (print . show)"True"
bifor_ (Left "Hello") print (print . show)"Hello"
Returns the size/length of a finite structure as an Int.
Basic usage:
bilength (True, 42)2
bilength (Right 42)1
bilength (BiList [1,2,3] [4,5])5
bilength (BiList [] [])0
On infinite structures, this function hangs:
> bilength (BiList [1..] [])
* Hangs forever *
Test whether the structure is empty.
Basic usage:
binull (18, 42)False
binull (Right 42)False
binull (BiList [] [])True
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.
Basic usage:
bior (True, False)True
bior (False, False)False
bior (Left True)True
Empty structures yield False:
bior (BiList [] [])False
A True value finitely far from the left end yields True (short circuit):
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 *
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.
Basic usage:
bisequence_ (print "Hello", print "World")"Hello""World"
bisequence_ (Left (print "Hello"))"Hello"
bisequence_ (Right (print "World"))"World"
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.
Basic usage:
bitraverse_ print (print . show) ("Hello", True)"Hello""True"
bitraverse_ print (print . show) (Right True)"True"
bitraverse_ print (print . show) (Left "Hello")"Hello"
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) asA 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)
bifold :: Monoid m => p m m -> mCombines the elements of a structure using a monoid.
bifold ≡ bifoldMap id idBasic 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}
bifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> mCombines the elements of a structure, given ways of mapping them to a common monoid.
bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) memptyBasic 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]
bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> cCombines 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 . toEitherListBasic 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 -> cCombines 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 . toEitherListNote 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.
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
Bifoldable ArgDefined in base-4.22.0.0 · Data.SemigroupBifoldable MapDefined in containers-0.8 · Data.Map.InternalBifoldable EitherDefined in base-4.22.0.0 · Data.BifoldableBifoldable Tuple2Defined in base-4.22.0.0 · Data.BifoldableClass 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:
bifoldr (flip const) (:) [] (undefined :: (Int, Word)) `seq` ()()foldr (:) [] (errorWithoutStackTrace "error!" :: (Int, Word)) `seq` ()*** Exception: error!
Bifoldable HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.InternalBifoldable ConstDefined in base-4.22.0.0 · Data.BifoldableBifoldable ConstantDefined in transformers-0.6.1.2 · Data.Functor.ConstantBifoldable (Tuple3 x)Defined in base-4.22.0.0 · Data.BifoldableBifoldable (K1 i)Defined in base-4.22.0.0 · Data.BifoldableBifoldable (Tuple4 x y)Defined in base-4.22.0.0 · Data.BifoldableBifoldable (Tuple5 x y z)Defined in base-4.22.0.0 · Data.BifoldableBifoldable (Tuple6 x y z w)Defined in base-4.22.0.0 · Data.BifoldableBifoldable (Tuple7 x y z w v)Defined in base-4.22.0.0 · Data.BifoldableA default definition of bifoldMap in terms of the Bitraversable operations.
bifoldMapDefault f g ≡
getConst . bitraverse (Const . f) (Const . g)bifor is bitraverse with the structure as the first argument. For a version that ignores the results, see bifor_.
Basic usage:
bifor (Left []) listToMaybe (find even)Nothing
bifor (Left [1, 2, 3]) listToMaybe (find even)Just (Left 1)
bifor (Right [4, 5]) listToMaybe (find even)Just (Right 4)
bifor ([1, 2, 3], [4, 5]) listToMaybe (find even)Just (1,4)
bifor ([], [4, 5]) listToMaybe (find even)Nothing
A default definition of bimap in terms of the Bitraversable operations.
bimapDefault f g ≡
runIdentity . bitraverse (Identity . f) (Identity . g)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 idBasic usage:
bisequence (Just 4, Nothing)Nothing
bisequence (Just 4, Just 5)Just (4,5)
bisequence ([1, 2, 3], [4, 5])[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
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:
bitraverse (t . f) (t . g) ≡ t . bitraverse f g
for every applicative transformation
t
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 apreserving 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 yBitraversable 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
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 gFor a version that ignores the results, see bitraverse_.
Basic usage:
bitraverse listToMaybe (find odd) (Left [])Nothing
bitraverse listToMaybe (find odd) (Left [1, 2, 3])Just (Left 1)
bitraverse listToMaybe (find odd) (Right [4, 5])Just (Right 5)
bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])Just (1,5)
bitraverse listToMaybe (find odd) ([], [4, 5])Nothing
Bitraversable ArgDefined in base-4.22.0.0 · Data.SemigroupBitraversable EitherDefined in base-4.22.0.0 · Data.BitraversableBitraversable Tuple2Defined in base-4.22.0.0 · Data.BitraversableClass 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:
(bitraverse pure pure undefined :: IO (Int, Word)) `seq` ()()(traverse pure (errorWithoutStackTrace "error!") :: IO (Int, Word)) `seq` ()*** Exception: error!
Bitraversable ConstDefined in base-4.22.0.0 · Data.BitraversableBitraversable ConstantDefined in transformers-0.6.1.2 · Data.Functor.ConstantBitraversable (Tuple3 x)Defined in base-4.22.0.0 · Data.BitraversableBitraversable (K1 i)Defined in base-4.22.0.0 · Data.BitraversableBitraversable (Tuple4 x y)Defined in base-4.22.0.0 · Data.BitraversableBitraversable (Tuple5 x y z)Defined in base-4.22.0.0 · Data.BitraversableBitraversable (Tuple6 x y z w)Defined in base-4.22.0.0 · Data.BitraversableBitraversable (Tuple7 x y z w v)Defined in base-4.22.0.0 · Data.Bitraversable