Skip to content

Instantly share code, notes, and snippets.

@evincarofautumn
Last active May 18, 2017 00:11
Show Gist options
  • Save evincarofautumn/ec7d316e91850275e3c8713dac13d5e9 to your computer and use it in GitHub Desktop.
Save evincarofautumn/ec7d316e91850275e3c8713dac13d5e9 to your computer and use it in GitHub Desktop.
Arbitrary-like API for randomness
import Control.Monad
import System.Random
class Roll k r where
roll :: k -> IO r
instance Roll Int Int where
roll = pure
instance (Roll k r, Random a, Integral a) => Roll (a -> k) r where
roll f = do
x <- randomIO
roll $ f $ (x `mod` 6) + 1
main :: IO ()
main = do
rolls <- replicateM 10000 $ roll $ \ x y -> x + y :: Int
let
mean = fromIntegral (sum (rolls :: [Int]))
/ fromIntegral (length rolls)
print (mean :: Double)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment