From: Ramakrishnan Muthukrishnan Date: Mon, 29 Dec 2014 06:14:55 +0000 (+0530) Subject: hw12: wip X-Git-Url: https://git.rkrishnan.org/frontends/@manifest?a=commitdiff_plain;h=e30ed55755e2cbe5e22de0a16313d7b97023532c;p=yorgey.git hw12: wip --- diff --git a/hw12/12-monads.pdf b/hw12/12-monads.pdf new file mode 100644 index 0000000..d94b06d Binary files /dev/null and b/hw12/12-monads.pdf differ diff --git a/hw12/Risk.hs b/hw12/Risk.hs new file mode 100644 index 0000000..b78ac10 --- /dev/null +++ b/hw12/Risk.hs @@ -0,0 +1,39 @@ +{-# LANGUAGE GeneralizedNewtypeDeriving #-} + +module Risk where + +import Control.Applicative +import Control.Monad.Random +import Control.Monad(replicateM, liftM) +import Data.List(sort) + +------------------------------------------------------------ +-- Die values + +newtype DieValue = DV { unDV :: Int } + deriving (Eq, Ord, Show, Num) + +first :: (a -> b) -> (a, c) -> (b, c) +first f (a, c) = (f a, c) + +instance Random DieValue where + random = first DV . randomR (1,6) + randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi)) + +die :: Rand StdGen DieValue +die = getRandom + +------------------------------------------------------------ +-- Risk + +type Army = Int + +data Battlefield = Battlefield { attackers :: Army, defenders :: Army } + +-- battle :: Battlefield -> Rand StdGen Battlefield +battle (Battlefield {attackers = a, defenders = d}) = + let rolla = replicateM (min (a - 1) 3) die + rolld = replicateM (min d 2) die + zipped = liftA2 zip rolla rolld + in +