Community
Modules 24

Control.Monad.Accum

Experimental
Computation type:
Accumulation (either append-only state, or writer with

the ability to read all previous input).

Binding strategy:
Binding a function to a monadic value monoidally

accumulates the subcomputations (that is, using <>).

Useful for:
Logging, patch-style tracking.
Zero and plus:
None.
Example type:
Accum w a

A note on commutativity

Some effects are commutative: it doesn't matter which you resolve first, as all possible orderings of commutative effects are isomorphic. Consider, for example, the reader and state effects, as exemplified by ReaderT and StateT respectively. If we have ReaderT r (State s) a, this is effectively r -> State s a ~ r -> s -> (a, s); if we instead have StateT s (Reader r) a, this is effectively s -> Reader r (a, s) ~ s -> r -> (a, s). Since we can always reorder function arguments (for example, using flip, as in this case) without changing the result, these are isomorphic, showing that reader and state are commutative, or, more precisely, commute with each other.

However, this isn't generally the case. Consider instead the error and state effects, as exemplified by MaybeT and StateT respectively. If we have MaybeT (State s) a, this is effectively State s (Maybe a) ~ s -> (Maybe a, s): put simply, the error can occur only in the result, but not the state, which always 'survives'. On the other hand, if we have StateT s Maybe a, this is instead s -> Maybe (a, s): here, if we error, we lose both the state and the result! Thus, error and state effects do not commute with each other.

As the MTL is capability-based, we support any ordering of non-commutative effects on an equal footing. Indeed, if you wish to use MonadState, for example, whether your final monadic stack ends up being @MaybeT (State s) a, StateT s Maybe a@, or anything else, you will be able to write your desired code without having to consider such differences. However, the way we implement these capabilities for any given transformer (or rather, any given transformed stack) is affected by this ordering unless the effects in question are commutative.

We note in this module which effects the accumulation effect does and doesn't commute with; we also note on implementations with non-commutative transformers what the outcome will be. Note that, depending on how the 'inner monad' is structured, this may be more complex than we note: we describe only what impact the 'outer effect' has, not what else might be in the stack.

Commutativity of accumulation

The accumulation effect commutes with the identity effect (IdentityT), reader, writer or state effects (ReaderT, WriterT, StateT and any combination, including RWST for example) and with itself. It does not commute with anything else.

3 generation diagnostics
  • unattached documentation comment at 305:7
  • unattached documentation comment at 307:7
  • unattached documentation comment at 309:7

Type class

class (Monoid w, Monad m) => MonadAccum w m

The capability to accumulate. This can be seen in one of two ways:

  • A MonadState which can only append (using <>); or

  • A MonadWriter (limited to tell) with the ability to view the result of all previous tells.

Laws

accum should obey the following:

  1. accum (const (x, mempty)) = pure x

  2. accum f *> accum g = @accum $ \acc -> let (_, v) = f acc (res, w) = g (acc <> v) in (res, v <> w)@

If you choose to define look and add instead, their definitions must obey the following:

  1. look *> look = look

  2. add mempty = pure ()

  3. add x *> add y = add (x <> y)

  4. add x *> look = look >>= \w -> add x $> w <> x

If you want to define both, the relationship between them is as follows. These are also the default definitions.

  1. look = accum $ \acc -> (acc, mempty)

  2. add x = accum $ \acc -> ('()', x)

  3. accum f = look >>= \acc -> let (res, v) = f acc in add v $> res

look :: m w

Retrieve the accumulated result so far.

add :: w -> m ()

Append a value to the result.

accum :: (w -> (a, w)) -> m a

Embed a simple accumulation action into the monad.

The Accum monad

type Accum w = AccumT w Identity

An accumulation monad (non-strict) parameterized by the type w of output to accumulate.

This monad is a more complex extension of both the reader and writer monads. The return function produces the output mempty, while @m >>= k uses the output of m@ both to extend the initial environment of k and to combine with the output of k:

<<images/bind-AccumT.svg>>

In applications requiring only the ability to accumulate an output and to inspect the output so far, it would be considerably more efficient to use a state monad.

runAccum :: Accum w a -> w -> (a, w)

Unwrap an accumulation computation as a (result, output) pair. (The inverse of accum.)

execAccum :: Accum w a -> w -> w

Extract the output from an accumulation computation.

  • execAccum m w = snd (runAccum m w)

evalAccum :: (Monoid w) => Accum w a -> w -> a

Evaluate an accumulation computation with the given initial output history and return the final value, discarding the final output.

  • evalAccum m w = fst (runAccum m w)

mapAccum :: ((a, w) -> (b, w)) -> Accum w a -> Accum w b

Map both the return value and output of a computation using the given function.

  • runAccum (mapAccum f m) = f . runAccum m

The AccumT monad transformer

newtype AccumT w m a

An accumulation monad parameterized by:

  • w - the output to accumulate.

  • m - The inner monad.

This monad transformer is a more complex extension of both the reader and writer monad transformers. The return function produces the output mempty, while m >>= k uses the output of m both to extend the initial environment of k and to combine with the output of k:

<<images/bind-AccumT.svg>>

In applications requiring only the ability to accumulate an output and to inspect the output so far, it would be considerably more efficient to use a state monad transformer.

AccumT w m is strict if and only if m is.

AccumT :: w -> m (a, w) -> AccumT w m a

runAccumT :: AccumT w m a -> w -> m (a, w)

Unwrap an accumulation computation. For example, in the call

(value, locals) <- runAccumT action globals

the action is fed an initial environment globals, and locals is the sum of all arguments to calls of add executed by the action.

execAccumT :: (Monad m) => AccumT w m a -> w -> m w

Extract the output from an accumulation computation.

  • execAccumT m w = liftM snd (runAccumT m w)

evalAccumT :: (Monad m, Monoid w) => AccumT w m a -> w -> m a

Evaluate an accumulation computation with the given initial output history and return the final value, discarding the final output.

  • evalAccumT m w = liftM fst (runAccumT m w)

mapAccumT :: (m (a, w) -> n (b, w)) -> AccumT w m a -> AccumT w n b

Map both the return value and output of a computation using the given function.

  • runAccumT (mapAccumT f m) = f . runAccumT m

readerToAccumT :: (Functor m, Monoid w) => ReaderT w m a -> AccumT w m a

Convert a read-only computation into an accumulation computation.

writerToAccumT :: WriterT w m a -> AccumT w m a

Convert a writer computation into an accumulation computation.

accumToStateT :: (Functor m, Monoid s) => AccumT s m a -> StateT s m a

Convert an accumulation (append-only) computation into a fully stateful computation.

Lifting helper type

newtype LiftingAccum (t :: (Type -> Type) -> Type -> Type) (m :: Type -> Type) (a :: Type)

A helper type to decrease boilerplate when defining new transformer instances of MonadAccum.

Most of the instances in this module are derived using this method; for example, our instance of ExceptT is derived as follows:

deriving via (LiftingAccum (ExceptT e) m) instance (MonadAccum w m) =>
 MonadAccum w (ExceptT e m)

Other functions

looks :: forall (a :: Type) (m :: Type -> Type) (w :: Type). (MonadAccum w m) => (w -> a) -> m a

Retrieve a function of the accumulated value.

Instances

19
  • instance (Monoid w, Monad m) => MonadAccum w (AccumT w m)
  • instance (MonadAccum w m) => MonadAccum w (MaybeT m)

    The accumulated value 'survives' an error: even if the computation fails to deliver a result, we still have an accumulated value.

  • instance (MonadAccum w m) => MonadAccum w (ContT r m)

    The continuation can see, and interact with, the accumulated value.

  • instance (MonadAccum w m) => MonadAccum w (ExceptT e m)

    The accumulated value 'survives' an exception: even if the computation fails to deliver a result, we still have an accumulated value.

  • instance (MonadAccum w m) => MonadAccum w (IdentityT m)
  • instance (MonadAccum w' m) => MonadAccum w' (CPSRWS.RWST r w s m)
  • instance (MonadAccum w' m, Monoid w) => MonadAccum w' (LazyRWS.RWST r w s m)
  • instance (MonadAccum w' m, Monoid w) => MonadAccum w' (StrictRWS.RWST r w s m)
  • instance (MonadAccum w m) => MonadAccum w (ReaderT r m)
  • instance (MonadAccum w m) => MonadAccum w (SelectT r m)

    The 'ranking' function gains the ability to accumulate ws each time it is called. The final result will include the entire log of all such calls.

  • instance (MonadAccum w m) => MonadAccum w (LazyState.StateT s m)
  • instance (MonadAccum w m) => MonadAccum w (StrictState.StateT s m)
  • instance (MonadAccum w' m) => MonadAccum w' (CPSWriter.WriterT w m)
  • instance (MonadAccum w' m, Monoid w) => MonadAccum w' (LazyWriter.WriterT w m)
  • instance (MonadAccum w' m, Monoid w) => MonadAccum w' (StrictWriter.WriterT w m)
  • instance (Functor t, Functor m, Functor a) => Functor (LiftingAccum t m a)
  • instance (Applicative t, Applicative m, Applicative a) => Applicative (LiftingAccum t m a)
  • instance (Monad t, Monad m, Monad a) => Monad (LiftingAccum t m a)
  • instance (MonadTrans t, Monad (t m), MonadAccum w m) => MonadAccum w (LiftingAccum t m)
Maintainer
koz.ross@retro-freedom.nz
Portability
GHC only
Copyright
(C) Koz Ross 2022, Manuel Bärenz 2021
License
BSD-3-Clause (see the LICENSE file)
Build record and source files

Community contribution. The service has not verified this documentation. The generator reported 6 diagnostics.

Target: Linux on x86-64. Some inferred types and resolved links are not available.

Generator: aihc-haddock-858b1951-web-1

Metadata snapshot: 032b29dc8ecd03eaae7b1a84a40ef8560125381762749b2f47333bc9a4f4bb8e

Open the dependency plan · Download the documentation model

Import a package

Enter a package name and an exact version from Hackage. The site contains imported versions only.