module Game.LambdaHack.Strategy
( Strategy, nullStrategy, liftFrequency
, (.|), reject, (.=>), only, bestVariant, renameStrategy, returN
) where
import Control.Monad
import Data.Text (Text)
import Game.LambdaHack.Utils.Frequency
import Game.LambdaHack.Msg
newtype Strategy a = Strategy { runStrategy :: [Frequency a] }
deriving Show
instance Monad Strategy where
return x = Strategy $ return $ uniformFreq "Strategy_return" [x]
m >>= f = normalizeStrategy $ Strategy $
[ toFreq name [ (p * q, b)
| (p, a) <- runFrequency x
, y <- runStrategy (f a)
, (q, b) <- runFrequency y
]
| x <- runStrategy m
, let name = "Strategy_bind (" <> nameFrequency x <> ")"]
instance MonadPlus Strategy where
mzero = Strategy []
mplus (Strategy xs) (Strategy ys) = Strategy (xs ++ ys)
normalizeStrategy :: Strategy a -> Strategy a
normalizeStrategy (Strategy fs) = Strategy $ filter (not . nullFreq) fs
nullStrategy :: Strategy a -> Bool
nullStrategy strat = null $ runStrategy strat
liftFrequency :: Frequency a -> Strategy a
liftFrequency f = normalizeStrategy $ Strategy $ return f
infixr 2 .|
(.|) :: Strategy a -> Strategy a -> Strategy a
(.|) = mplus
reject :: Strategy a
reject = mzero
infix 3 .=>
(.=>) :: Bool -> Strategy a -> Strategy a
p .=> m | p = m
| otherwise = mzero
only :: (a -> Bool) -> Strategy a -> Strategy a
only p s = normalizeStrategy $ do
x <- s
p x .=> return x
bestVariant :: Strategy a -> Frequency a
bestVariant (Strategy []) = mzero
bestVariant (Strategy (f : _)) = f
renameStrategy :: Text -> Strategy a -> Strategy a
renameStrategy newName (Strategy fs) = Strategy $ map (renameFreq newName) fs
returN :: Text -> a -> Strategy a
returN name x = Strategy $ return $ uniformFreq name [x]