我正在尝试编写一个蜘蛛纸牌播放器作为 Haskell 学习练习。
我的 main
函数将为每个游戏调用一次 playGame
函数(使用 mapM
),传入游戏编号和随机生成器(StdGen
)。 playGame
函数应返回一个 Control.Monad.State
monad 和一个 IO monad,其中包含一个显示游戏画面的 String
和一个 Bool
指示游戏是赢还是输。
如何将 State
monad 与 IO
monad 组合起来作为返回值? `playGame 的类型声明应该是什么?
playGame :: Int -> StdGen a -> State IO (String, Bool)
State IO(字符串, bool )
是否正确?如果不是,应该是什么?
在main
中,我计划使用
do
-- get the number of games from the command line (already written)
results <- mapM (\game -> playGame game getStdGen) [1..numberOfGames]
这是调用 playGame
的正确方法吗?
最佳答案
您想要的是 StateT s IO (String, Bool)
,其中 StateT
由 Control.Monad.State
提供(来自mtl
包)和 Control.Monad.Trans.State
(来自 transformers
包)。
这种普遍现象称为 monad 转换器,您可以在 Monad Transformers, Step by Step 中阅读对它们的精彩介绍。 .
有两种定义它们的方法。其中之一可以在 transformers
包中找到,该包使用 MonadTrans
类来实现它们。第二种方法可以在 mtl
类中找到,并为每个 monad 使用单独的类型类。
transformers
方法的优点是使用单个类型类来实现所有内容(已找到 here ):
class MonadTrans t where
lift :: Monad m => m a -> t m a
lift
有两个很好的属性,任何 MonadTrans
实例都必须满足:
(lift .) return = return
(lift .) f >=> (lift .) g = (lift .) (f >=> g)
这些是变相的仿函数定律,其中 (lift .) = fmap
、return = id
和 (>=>) = (.)
.
mtl
类型类方法也有其优点,有些事情只能使用 mtl
类型类来干净地解决,但缺点是每个 mtl
类型类都有自己的一套规则,在为其实现实例时必须记住。例如,MonadError
类型类(找到 here )定义为:
class Monad m => MonadError e m | m -> e where
throwError :: e -> m a
catchError :: m a -> (e -> m a) -> m a
这个类也有法律:
m `catchError` throwError = m
(throwError e) `catchError` f = f e
(m `catchError` f) `catchError` g = m `catchError` (\e -> f e `catchError` g)
这些只是变相的单子(monad)法则,其中 throwError = return
和 catchError = (>>=)
(单子(monad)法则是变相的类别法则,其中 return = id
和 (>=>) = (.)
)。
对于您的具体问题,编写程序的方式是相同的:
do
-- get the number of games from the command line (already written)
results <- mapM (\game -> playGame game getStdGen) [1..numberOfGames]
...但是当您编写 playGame
函数时,它看起来像:
-- transformers approach :: (Num s) => StateT s IO ()
do x <- get
y <- lift $ someIOAction
put $ x + y
-- mtl approach :: (Num s, MonadState s m, MonadIO m) => m ()
do x <- get
y <- liftIO $ someIOAction
put $ x + y
当您开始堆叠多个 monad 转换器时,这些方法之间存在更多差异,这些差异变得更加明显,但我认为现在这是一个好的开始。
关于haskell - 在 Haskell 中组合 monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10913835/