Safe Haskell | None |
---|

This module exports:

- The
`MonadState`

type class and its operations`state`

,`get`

and`put`

. - Instances of
`MonadState`

for the relevant monad transformers from the`transformers`

package (lazy`StateT`

, strict`StateT`

, lazy`RWST`

and strict`RWST`

). - A universal pass-through instance of
`MonadState`

for any existing`MonadState`

wrapped by a`MonadLayer`

. - The utility operations
`modify`

and`gets`

.

- class Monad m => MonadState s m | m -> s where
- modify :: MonadState s m => (s -> s) -> m ()
- gets :: MonadState s m => (s -> a) -> m a

# Documentation

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.

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

Embed a simple state action into the monad.

Return the state from the internals of the monad.

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.

`>>>`

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

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.