Haskell : Monads for States!

Demonstrate how to carry to implicit states with Monads :

import System.Random
import Control.Monad.State
type RandomState = State StdGen

getRandom ::(Random a) => RandomState a
getRandom = get >>= \g ->
let (a,g’) = random g
in put g’ >> return a

twoRands ::(Random a,Random b)=> RandomState (a,b)
twoRands = liftM2 (,) getRandom getRandom

getRandoms :: (Random a) =>RandomState [a]
getRandoms = getRandom >>= \a -> getRandoms >>= (\xs -> return (a:xs))

fullRands rand= getStdRandom (runState rand)

getRandom’ ::(Random a) => RandomState a
getRandom’ = do
g RandomState (a,b)
twoRands’ = do
b RandomState (a,b)
twoRands” = getRandom >>= \a->
getRandom >>= \b -> return (a,b)

threeRands :: (Random a,Random b,Random c)=> RandomState (a,b,c)
threeRands = do
(a,b) <- twoRands
c<- getRandom
return (a,b,c)

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s