haskell - Writer Monad 是否保证右关联连接?

标签 haskell monads writer

已在 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/

相关文章:

variables - 我如何记住 Haskell 中二叉搜索树的根

haskell - 解析器示例不适合我

list - 为什么 Haskell 不允许在推导中进行模式匹配?

java - 将多行写入java文件

python - Python csv writer 是否总是使用 DOS 行尾字符?

c++ - OpenCV - VideoWriter 生成带有 "repeated"图像的视频

haskell - 类型和数据构造函数中的类型参数

Haskell-如何在递归函数中跟踪计数器

Haskell-Stack:构建期间出现访问冲突错误

haskell - Haskell 中是否有任何运算符可以用 (>>) 折叠操作列表?