Created
January 3, 2012 10:59
-
-
Save Newky/1554464 to your computer and use it in GitHub Desktop.
Haskell random generator demonstrating state monad.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Random | |
newtype State s a = State { | |
runState :: s -> (a, s) | |
} | |
returnState :: a -> State s a | |
returnState a = State (\s-> (a, s)) | |
bindState :: State s a -> (a -> State s b) -> State s b | |
bindState m k = State (\s -> let (a, s') = runState m s | |
in runState ( k a ) s') | |
instance Monad (State s) where | |
return = returnState | |
(>>=) = bindState | |
getSt :: State s s | |
getSt = State $ \s -> (s, s) | |
putSt :: s -> State s () | |
putSt s = State $ \_ -> ((), s) | |
getAny :: (Random a) => State StdGen a | |
getAny = do | |
g <- getSt | |
(x, g') <- return $ random g | |
putSt g' | |
return x | |
getOne :: (Random a) => (a, a) -> State StdGen a | |
getOne bounds = do g <- getSt | |
(x, g') <- return $ randomR bounds g | |
putSt g' | |
return x | |
makeRandomValue :: StdGen -> (Int, StdGen) | |
makeRandomValue = runState (do | |
n <- getOne (1, 100) | |
return n) | |
main = do | |
g <- getStdGen | |
print $ fst $ makeRandomValue g | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment