【问题标题】:Is a state monad with two state variable types (in and out) still a monad?具有两种状态变量类型(输入和输出)的状态单子仍然是单子吗?
【发布时间】:2015-11-29 04:50:19
【问题描述】:

Haskell 的状态单子 State s a 迫使我在整个 do 块中保持相同类型的 s。但是由于 state monad 实际上只是一个函数,如果我将其定义为 State i o a = State (i -> (o, a))?。 returnbind 函数看起来与标准状态 monad 中的函数完全相同,但类型发生了变化:

return :: a -> State st st a
bind :: (State i o a) -> (a -> (State o o' b)) -> (State i o' b)

我认为不可能使用这个定义在 Haskell 中实现 Monad,因为它需要一个 State i o 类型的绑定(只有 a 可以更改)。但是这个问题不是关于 Haskell 而是关于这在技术上是否是一个单子。或者如果不是,它会是某种 monad 的超集(这样所有的 monad 法则仍然适用,但有一些额外的功能)?

我发现这在我正在研究的另一种语言中很有用,它基于 lambda 演算,所以我使用 Haskell 作为参考。我只是不希望这会在我希望单子定律适用的地方破坏其他东西。

【问题讨论】:

    标签: monads state-monad category-theory


    【解决方案1】:

    你正在寻找的是一个索引 Monad。参见例如category-extras中的定义:

    definition of an indexed Monad:

    class IxApplicative m => IxMonad m where
      ibind :: (a -> m j k b) -> m i j a -> m i k b
    

    State indexed Monad:

    class IxMonad m => IxMonadState m where
      iget :: m i i i
      iput :: j -> m i j ()
    

    【讨论】:

    • 其实就是这样。显然不是真正的 monad,而是接近的东西,但由于它与 state monad 具有完全相同的实现,我看不出它会如何违反任何 monad 规则或产生任何意外结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2014-06-28
    相关资源
    最近更新 更多