[Haskell-cafe] State Monad - using the updated state in an adhoc
manner
Brandon S. Allbery KF8NH
allbery at ece.cmu.edu
Thu Jan 8 00:06:40 EST 2009
On 2009 Jan 7, at 20:58, Phil wrote:
> -- 124353542542 is just an arbitrary seed
> main :: IO()
> main = do
> let x = evalState getRanq1 (ranq1Init 124353542542)
> print (x)
You're throwing away the state you want to keep by using evalState
there. But you're also missing the point of using State; done right
the evalState *is* what you want.
What you want to do is run all of your operations within State,
exiting it only when you're done:
> main = do
> print (evalState doRanqs (ranq1init 124353542542))
>
> doRanqs = do
> r <- getRanq1
> -- do something involving it
> another <- getRanq1
> -- do more stuff
Alternately you may use a tail recursive function or a fold, etc.,
depending on what exactly you're trying to accomplish.
You do *not* want to execState or runState every individual time you
want a random number; if you do that you'll have to carry the random
state around yourself (in effect you'd be rewriting the State monad by
hand, poorly). Stay in State and let it do the carrying for you.
--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university KF8NH
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090108/7821d06c/attachment.htm
More information about the Haskell-Cafe
mailing list