[Haskell-beginners] State Monad
Sumit Sahrawat, Maths & Computing, IIT (BHU)
sumit.sahrawat.apm13 at iitbhu.ac.in
Fri Apr 17 22:31:02 UTC 2015
A good exercise will be to re-implement State, and then use it. Take a look
here: http://en.wikibooks.org/wiki/Haskell/Understanding_monads/State.
This link will take you to a tutorial that takes you through the
implementation of State, and then uses it for random number generation.
Hope this helps. Enjoy !
On 18 April 2015 at 00:55, Thomas Jakway <tjakway at nyu.edu> wrote:
> I'm having some trouble using the state monad with a random number
> generator.
>
> I'm trying to follow the LYAH example (
> http://learnyouahaskell.com/for-a-few-monads-more) but apparently the
> state monad API has changed, so I'm using Control.Monad.Trans.State.Lazy
> (state monad from the transformers package). Side question: is using
> transformers a good idea? I've heard some people complain about mtl's
> performance, others don't seem to care. I'm far too new to be able to
> judge anything (does it even make sense to compare transformers vs. mtl?)
> but if one has overtaken the other I'd rather use that.
>
> Here's what I currently have:
> import Control.Monad.Trans.State.Lazy
> type GeneratorState = State StdGen
>
> genThree :: Int -> GeneratorState Int
> genThree listMax = do --highest index in the list
> let listMin = 0 :: Int --lowest index in the list
> generator <- get
> let (generatedMin, state) = randomR (listMin, listMax) generator
> return generatedMin
>
> Although it typechecks it doesn't seem like an improvement over just using
> StdGen by itself.
>
> What I think I should have:
> genThree :: Int -> GeneratorState Int
> genThree listMax = do --highest index in the list
> let listMin = 0 :: Int --lowest index in the list
> generatedMin <- state randomR (listMin, listMax)
> return generatedMin
>
> I feel like I really botched this--what am I missing?
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
--
Regards
Sumit Sahrawat
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150418/4baa3ea5/attachment.html>
More information about the Beginners
mailing list