liboleg-2010.1.9.0: An evolving collection of Oleg Kiselyov's Haskell modules

Control.StateAlgebra

Description

Implementing the State Monad as a term algebra

Synopsis

# Documentation

data Bind t f Source

Monadic actions are terms composed from the following constructors

Constructors

 Bind t f

Instances

 (RunBind m s x, RunState y s w) => RunBind (Bind m (x -> y)) s w (RunState m s a, RunState t s b) => RunState (Bind m (a -> t)) s b

data Return v Source

Constructors

 Return v

Instances

 RunBind (Return a) s a RunState (Return a) s a

data Get Source

Constructors

 Get

Instances

 RunBind Get s s RunState Get s s

data Put v Source

Constructors

 Put v

Instances

 RunBind (Put s) s () RunState (Put s) s ()

class RunBind t s a => RunState t s a | t s -> a whereSource

examples of terms

An example of an ill-formed term

An example of an ill-typed term The following term is ill-typed because it attempts to store both a boolean and a character in the state. Our state can have only one type.

The interpreter of monadic actions It takes the term `t` and the initial state of the type `s` and returns the final state and the resulting value. The type of the result, `a`, is uniquely determined by the term and the state

Methods

runst :: t -> s -> (s, a)Source

Instances

 RunState Get s s RunState (Put s) s () RunState (Return a) s a RunState (Statte s a) s a (RunState m s a, RunState t s b) => RunState (Bind m (a -> t)) s b

class RunBind m s a whereSource

Interpretation of the Bind action requires an auxiliary class This is due to the polymorphism of the monadic bind, which has the type

``` m a -> (a -> m b) -> m b
```

Note the polymorphism both in `a` (value type of the input monadic action) and `b` (value type of the resulting action)

Methods

runbind :: RunState t s b => m -> (a -> t) -> s -> (s, b)Source

Instances

 RunBind Get s s RunBind (Put s) s () RunBind (Return a) s a RunBind (Statte s a) s a (RunBind m s x, RunState y s w) => RunBind (Bind m (x -> y)) s w

data Statte s a Source

We can now run (interpret) our sample terms

term2 denoted the action of negating the current state and returning the original state

Now, we show that our term representation of the state monad is an instance of MonadState

Constructors

 forall t . RunState t s a => Statte t

Instances

 MonadState s (Statte s) Monad (Statte s) RunBind (Statte s a) s a RunState (Statte s a) s a

as_statte :: Statte s a -> Statte s aSource

We can write computations expressed by term1 and term2 using the normal monadic syntax

The following identity function is to resolve polymorphism, to tell that monadic terms below should use our representation of MonadState