polymorphic type in state of state monad

Tom Pledger Tom.Pledger@peace.com
Tue, 11 Mar 2003 08:34:06 +1300


Wang Meng writes:
 | Hi All,
 | 
 | Any one of your have the experience of defining a state of a state monad
 | as a polymorphic type?
 | I want to have:
 | 
 | > type State = Term a => [a]
 | > data M a = M (State -> IO(State,a))
 | 
 | GHC yields a error message "Illegal polymorphic type".
 | How to resolve this?



If you only want to vary the state type between separate monadic
computations, all you need to do is parameterise your datatype over
the state type:

> data M s a = M (s -> IO (s, a))

This is available in some libraries, such as
http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html

You could use it like this:

> import Control.Monad.State
> type M s = StateT s IO



If, on the other hand, you want to vary the state type *during* a
single monadic computation, it gets messy.  You could try one of the
following.

  - Declare a datatype with a branch for each instance of Term, and
    use this as the state type.

    > data State = TermType1 TermType1
    >            | TermType2 TermType2
    >            | ...
    >            | TermTypeN TermTypeN

  - Do something similar with an existential type.

    > data State = forall a . Term a => State a

  - Don't use monadic state at all, but instead pass the state around
    explicitly.

Regards,
Tom