我正在尝试使用 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
。这可能吗?
最佳答案
拥有多个相似的层实际上是一种情况,其中 mtl
方法(旨在使 lift
隐式)遇到了您提到的麻烦。因此您可以显式地使用 lift
。
lift :: Writer Struct Bool -> WriterT Collision (Writer Struct) Bool
因此
foo x = do lift (tell (S False)) ; return x
关于haskell - 作家 Monad 嵌套两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42590149/