Probability.hs 952 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Probability (Probability(..), readProbability, decide) where

import           System.Random
import           Text.Printf

data Probability = Probability Integer Int

readProbability :: String -> Either String Probability
readProbability input = case input of
  "0" -> Right (Probability 0 0)
  ('0':'.':rest) -> case reads rest of
    [(digits, "")] -> Right (Probability digits (length rest))
    _ -> failure
  "1" -> Right (Probability 1 0)
  ('1':'.':rest)
    | all (=='0') rest -> Right (Probability 1 0)
    | otherwise -> failure
  _ -> failure

  where failure = Left "Could not parse probability"

instance Show Probability where
  show (Probability digits 0) = show digits
  show (Probability digits exp) = "0." ++ printf "%0*d" exp digits

decide :: Probability -> IO Bool
decide (Probability digits exp) = do
  randomNumber <- randomRIO (0, (10^exp)-1)
  return $ randomNumber < digits