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.
It might help your confusion if you replace the more generic
Writer Stringwith the more concreteStringWriter:A
Writer String Intis just another way to say a tuple(Int, String). Look at the signature ofrunWriter, it converts from aWriter String Intto(Int, String):and the data constructor
Writer, which converts into the reverse direction:I am not exactly sure what you mean by that but for a monad it is essential that it works for all types, so the
ainStringWriter ais important, when you declare the monad instance. (Confusingly enough, you need it but don't write it:instance Monad StringWriter.)A couple of points:
Monoid w adoes not make sense, since theMonoidtypeclass has only one parameter:Monad (Writer w a)does not make sense, because the argument to theMonadtypeclass is not a type but a type constructor (with one argument). This is in contrast to theMonoidtypeclass which takes a concrete type (instead of a type constructor of one parameter). That is,instance Monad StringWriteris correct butinstance Monad (StringWriter Int)is not. Note thatStringWriter Intis a type butStringWriteris a type constructor taking one argument.It is not listed, because the function type declarations are not listed. You could enable the
InstanceSigsextension and write them explicitly: