haskell - 创建我自己的状态单子(monad)

标签 haskell monads state-monad

我了解如何使用单子(monad),但我并不真正掌握如何创建单子(monad)。所以我正在重新创建一个 State monad。

到目前为止,我已经创建了一个新类型 Toto(法语为 foo),并将其作为 Monad 的实例。现在我正在尝试为其添加“阅读器功能”。我创建了一个 TotoReader 类,它声明了一个“get”函数。但当我尝试实例化它时,一切都崩溃了。 GHC 告诉我它无法推断出 (m ~ r) (底部有完整的编译错误)。

但是当我创建顶级函数 get 时,一切都正常工作。

那么我如何在类中定义 get 函数,这真的是正确的方法吗?我不明白什么?

我的代码到目前为止

{-# OPTIONS -XMultiParamTypeClasses #-}
{-# OPTIONS -XFlexibleInstances #-}

newtype Toto s val = Toto { runToto :: s -> (val, s) }

toto :: (a -> (b,a)) -> Toto a b
toto = Toto

class (Monad m) => TotoReader m r where
    get :: m r

instance Monad (Toto a) where
    return a = toto $ \x -> (a,x)
    p >>= v  = toto $ \x ->
                    let (val,c) = runToto p x
                    in runToto (v val) c

instance TotoReader (Toto m) r where 
    get = toto $ \x -> (x, x) -- Error here

-- This is working
-- get :: Toto a b
-- get = toto $ \s -> (s,s)


pp :: Toto String String
pp = do 
    val <- get
    return $ "Bonjour de " ++ val

main :: IO ()
main = print $ runToto pp "France"

编译错误

test.hs:19:11:
    Could not deduce (m ~ r)
    from the context (Monad (Toto m))
      bound by the instance declaration at test.hs:18:10-30
      `m' is a rigid type variable bound by
          the instance declaration at test.hs:18:10
      `r' is a rigid type variable bound by
          the instance declaration at test.hs:18:10
    Expected type: Toto m r
      Actual type: Toto m m
    In the expression: toto $ \ x -> (x, x)
    In an equation for `get': get = toto $ \ x -> (x, x)
    In the instance declaration for `TotoReader (Toto m) r'

最佳答案

让我们使用 ghci 来检查种类:

*Main> :k Toto
Toto :: * -> * -> *

Toto 采用两个类型参数:环境类型和返回类型。如果r是环境,Toto r将是monad类型构造函数。

*Main> :k TotoReader
TotoReader :: (* -> *) -> * -> Constraint

TotoReader 采用两个类型参数:monad 类型构造函数和环境类型,在我们的例子中分别是 Toto rr

因此,实例声明应该类似于:

instance TotoReader (Toto r) r where 
    get = toto $ \x -> (x, x)

关于haskell - 创建我自己的状态单子(monad),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742658/

相关文章:

haskell - 无法将类型 ‘[Char]’ 与 ‘Data.Text.Internal.Text’ 匹配

Haskell State Monad 和 Binary 不输出所有内容

haskell - 这个 State monad 代码是如何工作的?

multithreading - 超时的 Haskell 函数

Haskell替换列表中的元素

haskell - 在 Haskell 中导出任意函数

haskell - 生成具有恒定堆栈空间的随机向量

haskell - 是否有一种更易读的方法来重写这个纯函数以使用 Writer Monad?

haskell - 在 ghci 中用花括号做 block 会引发错误

haskell - 将 ST monad 重新打扮成类似于 State monad 的东西