Safe Haskell | None |
---|
This module exports:
- The
MonadState
type class and its operationsstate
,get
andput
. - Instances of
MonadState
for the relevant monad transformers from thetransformers
package (lazyStateT
, strictStateT
, lazyRWST
and strictRWST
). - A universal pass-through instance of
MonadState
for any existingMonadState
wrapped by aMonadLayer
. - The utility operations
modify
andgets
.
- 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.
>>>
: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.