Writing for both State and StateT

Jon Cast jcast@ou.edu
Tue, 22 Apr 2003 16:44:49 -0500


Mark Carroll <mark@chaos.x-philes.com> wrote:
> On Tue, 22 Apr 2003, Jon Cast wrote:

> > When you have two identical methods like this, you can try removing
> > the type from one and seeing what hugs or ghci thinks the type is.
> > Then, you can specialize that if you want.

> Unfortunately, in this case, with that function in isolation I get,

>     Ambiguous type variable(s) `s', `m'
>         in the constraint `MonadState s m'
>     arising from use of `get' ....

Ah, yes the good old monomorphism restriction.  Should have thought
about that.  The way around this is to make the declaration a function:

> next_random_probability () =
>    do old_rng <- get
>       let (random_probability, new_rng) = randomR (0, 1) old_rng
>       put new_rng
>       return random_probability

This will typecheck, giving most general type (MonadState s m, Num a,
Random a, RandomGen s) => () -> m a, according to ghci.  Then, you can
take off the argument type to get the resulting type.

<snip>

Jon Cast