Recent Changes - Search:

yurusanai.de

State Transformer Monad

Download: state.f

The following implementation of a state transformer monad was provided by Julien Oster. It uses operators similar to those of the Haskell programming language.

 # unitState(value)
 #   takes a value and returns a State Monad containing that value

 unitState(x) = State(\ s . ST(s, x))


 # bind: statemonad >>= function
 #   chains operations in the State Monad together, binding the value of
 #   the given State Monad to the given function

 op(>>=)(State(\m), \f) = State(\ s .
   let ST(s', x') = m(s), State(\m') = f(x')
   in m'(s') )


 # anonymous bind: statemonad1 >>- statemonad2
 #   chains operations in the State Monad together, but throws away the
 #   value of the first State Monad by just retaining the value of the
 #   second.

 op(>>-)(State(\m), State(\m2)) = State(\ s .
     let ST(s', x') = m(s)
     in m2(s') )


 # readState and writeState read and write the current State

 readState = State(\ s . ST(s, s))
 writeState(x) = State(\ s . ST(x, Empty))


 # runState(state, initial)
 #   runState takes a State Monad and an initial value for the State
 #   and "runs" the Monad, returning its final value

 runState(state, initial) = let State(s) = state in s(initial)


 # a State Monad example, which performs a simple calculation by manipulating
 # and reading the contained State

 examplestate =
   readState         >>= \ a .          # read state
   unitState  (a+1)  >>= \ b .          # add 1
   writeState (b)    >>-                # and write back to state
   unitState  (2)    >>= \ c .
   readState         >>= \ d .          # read state
   unitState  (c*d+a)                   # multiply by 2 and add original state


 main(_,_) = runState(examplestate, 1000)

< Quick sort | Examples | Reverse arguments >

Edit - History - Print - Recent Changes - Search
Page last modified on December 14, 2007, at 07:07 PM