10

在 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" ++ "") ++ "!"
4

2 回答 2

7

是的,这确实是不真实的。从源代码

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)

所以 s 的链mappend将镜像 s 的链(>>=)

于 2012-01-04T18:21:52.807 回答
1

Writer [a]不保证右关联连接,但您可以通过 . 获得保证右关联连接Writer (Endo [a])

于 2014-12-26T01:31:58.750 回答