I am trying to get a better understanding of Monads and I am currently looking into the Write Monad in http://learnyouahaskell.com/for-a-few-monads-more#writer
I don't understand its type declaration that seemingly consists of two types, nor do I understand its type constraint.
In the examples they specify that:
newtype Writer w a = Writer { runWriter :: (a, w) }
instance (Monoid w) => Monad (Writer w) where
return x = Writer (x, mempty)
(Writer (x,v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `mappend` v')
In action it looks like this:
ghci> runWriter (return 3 :: Writer String Int)
(3,"")
ghci> runWriter (return 3 :: Writer (Sum Int) Int)
(3,Sum {getSum = 0})
ghci> runWriter (return 3 :: Writer (Product Int) Int)
(3,Product {getProduct = 1})
But why does it return Writer String Int
rather than a tupple of these elements, I wonder?
Could I have made a Monad type (e.g. Writer2) that would return Writer String Int Float
?
Furthermore it confuses me why the instantiation only takes (Monoid w) => Monad (Writer w)
rather than (Monoid w a) => Monad (Writer w a)
. And why isn't the w
listed in the Monad binding and return methods, like a
would be included in the type signatur for the type constraint (Num a) => ...
This might be because I have some conceptual shortcoming in this area.