Last active
August 29, 2015 14:02
-
-
Save LouisJB/1688bb14a46f00d4cbf2 to your computer and use it in GitHub Desktop.
basic haskell randoms and io
This file contains hidden or 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
module Main( main ) where | |
import System.Environment | |
import System.Random | |
import Text.Printf | |
import Control.Monad | |
data Player = PlayerA | PlayerB | |
deriving (Show, Eq) | |
main :: IO () | |
main = do | |
let noOfRounds = 100 | |
let n = 10 | |
gen <- newStdGen | |
let rnds = randoms gen :: [Int] | |
rnds2 <- rands | |
rs1 <- sequence [playRound 0 0 | _ <- [1 .. noOfRounds] ] | |
printf "PlayRound: noOfRounds %d \n" (noOfRounds) | |
let noOfPlayerAWins = count playerAPred rs1 | |
printf "Player A wins: %d \n" (noOfPlayerAWins) | |
print rs1 | |
print "Replicated (pure)" | |
rs2 <- replicateM noOfRounds (playRound2 rnds2 0 0) | |
print rs2 | |
x <- replicateM 3 (rollDice 6) | |
print "Dice Rolls:" | |
print x | |
playerAPred x = x == PlayerA | |
count pred = length . filter pred | |
playRound :: Int -> Int -> IO Player | |
playRound xLast yLast = do | |
x <- randomRIO (1 :: Int, 6) | |
y <- randomRIO (1 :: Int, 6) | |
if x < xLast then | |
return PlayerB | |
else if y < yLast then | |
return PlayerA | |
else playRound x y | |
playRound2 :: [Int] -> Int -> Int -> IO Player | |
playRound2 (x : y : rs) xLast yLast = | |
if x < xLast then | |
return PlayerB | |
else if y < yLast then | |
return PlayerA | |
else playRound2 rs x y | |
rollDice :: Int => IO Int | |
rollDice n = getStdRandom (randomR (1, n)) | |
rands :: () => IO [Int] | |
rands = do | |
g <- newStdGen | |
let rnds = randoms g :: [Int] | |
return rnds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment