layers-0.1: Modular type class machinery for monad transformer stacks.

Safe HaskellNone



This module exports:

  1. The MonadState type class and its operations state, get and put.
  2. Instances of MonadState for the relevant monad transformers from the transformers package (lazy StateT, strict StateT, lazy RWST and strict RWST).
  3. A universal pass-through instance of MonadState for any existing MonadState wrapped by a MonadLayer.
  4. The utility operations modify and gets.



class Monad m => MonadState s m | m -> s whereSource

A pure functional language cannot update values in place because it violates referential transparency. A common idiom to simulate such stateful computations is to "thread" a state parameter through a sequence of functions:

This approach works, but such code can be error-prone, messy and difficult to maintain. The MonadState interface hides the threading of the state parameter inside the binding operation, simultaneously making the code easier to write, easier to read and easier to modify.

Minimal complete definition: state or both get and put.


state :: (s -> (a, s)) -> m aSource

Embed a simple state action into the monad.

get :: m sSource

Return the state from the internals of the monad.

put :: s -> m ()Source

Replace the state inside the monad.


(MonadLayer m, MonadState s (Inner m)) => MonadState s m 
(MonadState s f, MonadState s g) => MonadState s (Product f g) 
Monad m => MonadState s (StateT s m) 
Monad m => MonadState s (StateT s m) 
(Monad m, Monoid w) => MonadState s (RWST r w s m) 
(Monad m, Monoid w) => MonadState s (RWST r w s m) 

modify :: MonadState s m => (s -> s) -> m ()Source

Monadic state transformer.

Maps an old state to a new state inside a state monad. The old state is thrown away.

>>> :t modify ((+1) :: Int -> Int)
modify (...) :: (MonadState Int a) => a ()

This says that modify (+1) acts over any Monad that is a member of the MonadState class with an Int state.

gets :: MonadState s m => (s -> a) -> m aSource

Gets specific component of the state, using a projection function supplied.