【问题标题】:Writer Monad Nested TwiceWriter Monad 嵌套两次
【发布时间】:2017-03-03 23:29:31
【问题描述】:

我正在尝试使用 Monad Transformers 两次嵌套 writer monad。这是一个草图:

import Control.Monad.Identity
import Control.Monad.Writer

data Struct = S Bool

instance Monoid Struct where
    mempty =  S True
    mappend (S a) (S b) = S (a && b)

data Collision = C Bool

instance Monoid Collision where
    mempty =  C False
    mappend (C a) (C b) = C (a || b)

type CSInt = WriterT Collision (WriterT Struct Identity) Int

foo :: Int -> CSInt
foo x = do (tell (S False)) ; return x

foo 函数无法编译,因为我需要在 Struct monad 上使用 tell,而不是 Collision。有可能吗?

【问题讨论】:

    标签: haskell monads monad-transformers writer-monad


    【解决方案1】:

    实际上,有多个相似的层是mtl 方法的一种情况,该方法旨在使lift 隐含,正如您提到的那样有麻烦。所以你可以明确地使用lift

    lift :: Writer Struct Bool -> WriterT Collision (Writer Struct) Bool
    

    这样

    foo x = do lift (tell (S False)) ; return x
    

    【讨论】:

    • 谢谢。如果我可以问一个后续问题。我如何定义函数展开所有这些,类似于runWriter。签名:runW :: CSInt -> (Int, Bool, Bool)
    • 你可以使用runWriter/runWriterT,或者只是对CSInt进行模式匹配(参见WriterT的定义)。
    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多