undefined.
Eventually, the complete
version will be made available.
A Generic State Transformer
This file goes with Monads2.lhs.
Since state is a handy thing to have, the Haskell standard library includes a module Control.Monad.State that defines a parameterized version of the state-transformer monad. This file is a simplified version of that library.
This module includes an explicit export list. As a result, only the types and functions listed below will be visible to clients of the module. Furthermore, the type State is exported abstractly, i.e. without its data constructor S. That means that clients of this module cannot use S, not even for pattern matching.
> module State (State, get, put, modify, runState, evalState, execState) where
> import Control.Monad (ap,liftM)The type definition for a generic state transformer is very simple, and almost identical to the ST2 type from before:
This type is a parameterized state-transformer monad where the state is denoted by type s and the return value of the transformer is the type a. We make the above a monad by declaring it to be an instance of the Monad typeclass
Starting with GHC 7.10, all monads must also be a member of Functor and Applicative. However, we can use functions from Control.Monad to define these instances in a generic way. (You might try to redefine them yourself for fun!)
There are two other ways of evaluating the state monad. The first only returns the final result,
and the second only returns the final state.
Accessing and Modifying State
Since our notion of state is generic, it is useful to write get and put functions with which one can access and modify the state. We can easily get the current state via
That is, get denotes an action that leaves the state unchanged but returns the state itself as a value. Note that although get does not have a function type (unless you peek under the covers of State), we consider it a monadic "action".
Dually, to update the state to some new value s' we can write the function
which denotes an action that ignores (i.e., blows away) the old state and replaces it with s'. Note that the put s' is an action that itself yields nothing interesting (that is, merely the unit value).
For convenience, there is also the modify function that maps an old state to a new state inside a state monad. The old state is thrown away.
CIS 552: Advanced Programming