Data.Traversable.Compat

base-compat-0.14.1: A compatibility layer for base

Safe Haskell | Trustworthy
Language | Haskell2010

Data.Traversable.Compat

Synopsis

- module Data.Traversable
- mapAccumM :: (Monad m, Traversable t) => (s -> a -> m (s, b)) -> s -> t a -> m (s, t b)
- forAccumM :: (Monad m, Traversable t) => s -> t a -> (s -> a -> m (s, b)) -> m (s, t b)

# Documentation

module Data.Traversable

mapAccumM :: (Monad m, Traversable t) => (s -> a -> m (s, b)) -> s -> t a -> m (s, t b) #

The `mapAccumM` function behaves like a combination of `mapM` and `mapAccumL` that traverses the structure while evaluating the actions and passing an accumulating parameter from left to right. It returns a final value of this accumulator together with the new structure. The accumulator is often used for caching the intermediate results of a computation.

@since base-4.18.0.0

#### Examples

Expand

Basic usage:

    >>> let expensiveDouble a = putStrLn ("Doubling " <> show a) >> pure (2 * a)
    >>> :{
    mapAccumM (\cache a -> case lookup a cache of
        Nothing -> expensiveDouble a >>= \double -> pure ((a, double):cache, double)
        Just double -> pure (cache, double)
        ) [] [1, 2, 3, 1, 2, 3]
    :}
    Doubling 1
    Doubling 2
    Doubling 3
    ([(3,6),(2,4),(1,2)],[2,4,6,2,4,6])

forAccumM :: (Monad m, Traversable t) => s -> t a -> (s -> a -> m (s, b)) -> m (s, t b) #

`forAccumM` is `mapAccumM` with the arguments rearranged.

@since base-4.18.0.0