Created
July 10, 2015 14:48
-
-
Save orchid-hybrid/916b91a7a763620482e4 to your computer and use it in GitHub Desktop.
State and Rand Commute
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
{-# LANGUAGE GeneralizedNewtypeDeriving, NoMonomorphismRestriction #-} | |
import Control.Monad | |
import Control.Monad.State | |
import Control.Monad.Random | |
newtype SR g s a = SR { unSR :: RandT g (State s) a } | |
deriving (Monad, Applicative, Functor) | |
runSR m = do | |
g <- newStdGen | |
return $ runState (runRandT (unSR m) g) False | |
newtype RS g s a = RS { unRS :: StateT s (Rand g) a } | |
deriving (Monad, Applicative, Functor) | |
runRS m = do | |
g <- newStdGen | |
return $ runRand (evalStateT (unRS m) False) g | |
t1 :: RandomGen g => SR g Bool [Either Int Bool] | |
t1 = do | |
r1 <- SR (getRandomR (1::Int,6)) | |
b1 <- SR (lift get) | |
SR (lift $ modify not) | |
r2 <- SR (getRandomR (1::Int,6)) | |
b2 <- SR (lift get) | |
r3 <- SR (getRandomR (1::Int,6)) | |
return [Left r1,Right b1,Left r2,Right b2,Left r3] | |
t2 :: RandomGen g => RS g Bool [Either Int Bool] | |
t2 = do | |
r1 <- RS (lift $ getRandomR (1::Int,6)) | |
b1 <- RS (get) | |
RS (modify not) | |
r2 <- RS (lift $ getRandomR (1::Int,6)) | |
b2 <- RS (get) | |
r3 <- RS (lift $ getRandomR (1::Int,6)) | |
return [Left r1,Right b1,Left r2,Right b2,Left r3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment