已在 Validations in Haskell 中声明使用 Writer
保证右关联连接。然而,这个例子似乎另有说明。正确答案是什么?
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Writer
import Data.String
data TM = TMempty
| TMappend TM TM
| TMfromString String
instance IsString TM where
fromString = TMfromString
instance Monoid TM where
mempty = TMempty
mappend = TMappend
instance Show TM where
showsPrec d TMempty = showString "\"\""
showsPrec d (TMfromString s) = showString $ show s
showsPrec d (TMappend a b) = showParen (d > 0) $
showsPrec 1 a .
showString " ++ " .
showsPrec 0 b
theWriter :: Writer TM ()
theWriter = do
tell "Hello"
replicateM_ 2 $ tell "World"
tell "!"
main = print $ execWriter theWriter
产生:
"Hello" ++ ("World" ++ "World" ++ "") ++ "!"
最佳答案
是的,这确实是不真实的。来自 source code :
m >>= k = WriterT $ do
~(a, w) <- runWriterT m
~(b, w') <- runWriterT (k a)
return (b, w `mappend` w')
...
-- | @'tell' w@ is an action that produces the output @w@.
tell :: (Monoid w, Monad m) => w -> WriterT w m ()
tell w = WriterT $ return ((), w)
所以
mappend
的链s 将反射(reflect) (>>=)
的链s。
关于haskell - Writer Monad 是否保证右关联连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8731858/