[Haskell-beginners] Random Numbers with the State Monad
Marcin Mrotek
marcin.jan.mrotek at gmail.com
Fri Feb 12 13:26:36 UTC 2016
Hello,
You have this type error:
Couldn't match expected type ‘StateT
StdGen
Data.Functor.Identity.Identity Integer’
with actual type ‘g1 -> (Integer, g1)’
It's because you're trying to use a `(s -> (a,s))` function
"unwrapped" where GHC expects it "wrapped" in a StateT.
The type of `state` from Control.Monad.State (mtl package) is:
state :: (s -> (a, s)) -> m a
so it could solve your mismatch, turning `g1 -> (Integer, g1)` into
`StateT StdGen Identity Integer`, like:
np <- state (randomR (1, maxRandPlayers))
Alternatively, if you don't want to use mtl, you can use `StateT`s
constructor directly. It's type is:
StateT :: (s -> m (a, s)) -> StateT s m a
so you'd have to compose `randomR` with `return` (or `pure`) first:
np <- StateT (return . randomR (1, maxRandPlayers))
Best regards,
Marcin Mrotek
More information about the Beginners
mailing list