它被声称在Haskell 中的验证 https://stackoverflow.com/questions/8721609/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" ++ "") ++ "!"
是的,这确实是不真实的。来自源代码 http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/src/Control-Monad-Trans-Writer-Lazy.html:
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 将镜像链(>>=)
s.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)