Skip to content

Instantly share code, notes, and snippets.

@orchid-hybrid
Created July 10, 2015 14:48
Show Gist options
  • Save orchid-hybrid/916b91a7a763620482e4 to your computer and use it in GitHub Desktop.
Save orchid-hybrid/916b91a7a763620482e4 to your computer and use it in GitHub Desktop.
State and Rand Commute
{-# 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