Guest User

Untitled

a guest
Dec 11th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.10 KB | None | 0 0
  1. module Dice where
  2.  
  3. import Data.List as L
  4. import Data.Ord (comparing)
  5. import Data.Ratio
  6.  
  7. newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving Show
  8.  
  9. instance Functor Prob where
  10. fmap f (Prob xs) = Prob $ map (\(x,p) -> (f x, p)) xs
  11.  
  12. flatten :: Prob (Prob a) -> Prob a
  13. flatten (Prob xs) = Prob $ concat $ map multAll xs
  14. where multAll (Prob xxs, p) = map (\(x,r) -> (x,p*r)) xxs
  15.  
  16. instance Monad Prob where
  17. return x = Prob [(x,1%1)]
  18. m >>= f = flatten (fmap f m)
  19. fail _ = Prob []
  20.  
  21. dice :: Prob Int
  22. dice = Prob [(1, 1%6), (2, 1%6), (3, 1%6), (4, 1%6), (5, 1%6), (6, 1%6)]
  23.  
  24. roll6 :: Prob Bool
  25. roll6 = do
  26. a <- dice
  27. b <- dice
  28. c <- dice
  29. d <- dice
  30. e <- dice
  31. f <- dice
  32. return (all (== 1) [a,b,c,d,e,f])
  33.  
  34. distinct :: (Ord a) => Prob a -> Prob a
  35. distinct xs = let x = L.groupBy (\x y -> fst x == fst y) . L.sortBy (comparing fst) . getProb $ xs
  36. in Prob $ map (L.foldl1' addTup) x
  37. where addTup (a, p) (_, r) = (a, p+r)
Add Comment
Please, Sign In to add comment