haskell - 在 Haskell 中组合 monad

标签 haskell io state-monad

我正在尝试编写一个蜘蛛纸牌播放器作为 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),其中 StateTControl.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 .) = fmapreturn = 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 = returncatchError = (>>=) (单子(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/

相关文章:

适用于小型 Twitter 客户端的 Haskell IO cli 菜单

haskell - 在 Mac 上安装 Haskell 时使用 NonZeroExit 77 构建失败,ghcup --cache install”失败

haskell - 我可以要求 GHC 在开发过程中为每个模块导入 Debug.Trace 吗?

f# - 状态单子(monad)如何绑定(bind)到外部上下文中

haskell - 索引单子(monad)的高阶编码如何工作?

haskell - 无法理解 State Monad 如何在此代码中获取它的状态

java - 如何在 Haskell 中使用指向父子项的指针编写对象树?

c - fclose 上的段错误?

c++ - 如何从 ASCII 文本文件中读取(小)整数到 C++ 中足够的数据数组

io - 我如何轮询 std::net::UdpSocket?