Monads

Posted on 2015-08-24 19:16:47 +0900 in Functional Programming Haskell CIS194

Lecture Contents

Type class really gives one good intuition about Monad.

Intuitively, it is this ability to use the output from previous computations to decide what computations to run next that makes Monad more powerful than Applicative. The structure of an Applicative computation is fixed, whereas the structure of a Monad computation can change based on intermediate results. This also means that parsers built using an Applicative interface can only parse context-free languages; in order to parse context-sensitive languages a Monad interface is needed

Category theory gives some theorems behind Monad.

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

Home Work

Exercise 2
battle :: Battlefield -> Rand StdGen Battlefield
battle b = do
    (aStream :: [DieValue]) <- getRandoms
    (bStream :: [DieValue]) <- getRandoms
    let rollPairs = zip (sort . take numAttackRolls   $ aStream)
                        (sort . take numDefenderRolls $ bStream)
    return $ foldl' (\newB (attackRoll, defendRoll) ->
                        if attackRoll > defendRoll
                        then newB { defenders = defenders newB - 1}
                        else newB { attackers = attackers newB - 1})
                    b
                    rollPairs
  where
    numAttackRolls   = min 3 (attackers b - 1)
    numDefenderRolls = min 2 (defenders b)
Exercise 3
invade :: Battlefield -> Rand StdGen Battlefield
invade bf@(Battlefield a b)
  | a == 1 || b == 0 = return bf
  | otherwise = battle bf >>= invade
Exercise 4
successProb :: Battlefield -> Rand StdGen Double
successProb bf = do
  let num = 10000
  results <- replicateM num (invade bf)
  return $ fromIntegral (wins results) / fromIntegral num
  where wins = length . filter ((==0) . defenders)

Test code:

*Risk> evalRandIO  $ successProb $ Battlefield 2 3
0.1338
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | Applicative functors, Part II »

Hide Comments

comments powered by Disqus