Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created November 28, 2014 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/56be03881de4f65f7f29 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/56be03881de4f65f7f29 to your computer and use it in GitHub Desktop.
Coin tossing
import Data.List (all)
import Data.Ratio
newtype Prob a = Prob { getProb :: [(a, Rational)] }
instance Functor Prob where
fmap f (Prob xs) = Prob $ map (\(x, p) -> (f x, p)) xs
flatten :: Prob (Prob a) -> Prob a
flatten (Prob xs) = Prob $ concat $ map multAll xs
where multAll (Prob innerxs, p) = map (\(x, r) -> (x, p * r)) innerxs
instance Monad Prob where
return x = Prob [(x, 1%1)]
m >>= f = flatten (fmap f m)
fail _ = Prob []
data Coin = Heads | Tails deriving (Show, Eq)
coin :: Prob Coin
coin = Prob [(Heads, 1%2), (Tails, 1%2)]
loadedCoin :: Prob Coin
loadedCoin = Prob [(Heads, 1%10), (Tails, 9%10)]
flipThree :: Prob Bool
flipThree = do
a <- coin
b <- coin
c <- loadedCoin
return (all (==Tails) [a,b,c])
main = do
print $ getProb flipThree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment