Created
November 28, 2014 08:55
-
-
Save EmmanuelOga/56be03881de4f65f7f29 to your computer and use it in GitHub Desktop.
Coin tossing
This file contains 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
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