It was claimed in Validations in Haskell that use of a Writer
guarantees right-associative concatenation. However, this example seems to show otherwise. What's the correct answer?
{-# 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
Produces:
"Hello" ++ ("World" ++ "World" ++ "") ++ "!"
showsPrec
. – BradshawreplicateM_
withreplicateM
, the output becomes"Hello" ++ ("World" ++ ("World" ++ "" ++ "") ++ "") ++ "!"
– Gopherwoodsequence
andsequence_
:sequence = foldr (liftM2 (:)) (return [])
butsequence_ = foldr (>>) (return ())
; the former generates more binds because it does things with the results. – Claycomb>>
is supposed to be associative. But I am not a monadic lawyer. – BradshawWriter w
will follow the Monad laws. But non-right-associativemappend
s are usually inefficient. – Claycomb