| Safe Haskell | None |
|---|
Control.Monad.Interface.State
Description
This module exports:
- The
MonadStatetype class and its operationsstate,getandput. - Instances of
MonadStatefor the relevant monad transformers from thetransformerspackage (lazyStateT, strictStateT, lazyRWSTand strictRWST). - A universal pass-through instance of
MonadStatefor any existingMonadStatewrapped by aMonadLayer. - The utility operations
modifyandgets.
- 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.
Methods
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.
Instances
| (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.