From: Ramakrishnan Muthukrishnan Date: Mon, 29 Dec 2014 07:02:21 +0000 (+0530) Subject: hw12: solution to exercise 2 X-Git-Url: https://git.rkrishnan.org/(%5B%5E?a=commitdiff_plain;h=8dcef3b4c30b76c85cf6052e43d82fc7d84fa2b6;p=yorgey.git hw12: solution to exercise 2 --- diff --git a/hw12/Risk.hs b/hw12/Risk.hs index b78ac10..965c7c7 100644 --- a/hw12/Risk.hs +++ b/hw12/Risk.hs @@ -5,7 +5,7 @@ module Risk where import Control.Applicative import Control.Monad.Random import Control.Monad(replicateM, liftM) -import Data.List(sort) +import Data.List(sortBy) ------------------------------------------------------------ -- Die values @@ -30,10 +30,17 @@ type Army = Int data Battlefield = Battlefield { attackers :: Army, defenders :: Army } --- battle :: Battlefield -> Rand StdGen Battlefield +newBattlefield :: Battlefield -> [DieValue] -> [DieValue] -> Battlefield +newBattlefield battlefield rollA rollB = + let pairList = zip (sortBy (flip compare) rollA) (sortBy (flip compare) rollB) + in + foldr (\(a, d) acc -> if a > d then Battlefield (attackers acc) ((defenders acc) - 1) + else Battlefield ((attackers acc) - 1) (defenders acc)) battlefield pairList + + +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 - + liftA2 (newBattlefield (Battlefield a d)) rolla rolld