[Haskell-cafe] writer monad help
Jules Bean
jules at jellybean.co.uk
Fri May 18 07:57:50 EDT 2007
iskaldur wrote:
> I'm trying to learn to use the Writer Monad, but I'm having trouble with the
> following very simple program:
>
> import Control.Monad.Writer
> foo :: Writer String Int
> foo = tell "hello"
>
> Basically, I was trying to figure out the 'tell' function, so I want foo to
> return ((), "hello").
You want foo to return ((),"hello")? Well, then, it has type Writer
String (), not Writer String Int :-)
>
> But I get this error:
> Couldn't match `Int' against `()'
> Expected type: Writer String Int
> Inferred type: Writer String ()
> In the application `tell "hello"'
> In the definition of `foo': foo = tell "hello"
>
> What am I supposed to do? Write my own version of tell for Writer String
> Int? How exactly do I do this?
tell doesn't return anything. So tell "hello" has type Writer String ().
There isn't anything sensible for it to return, is there?
If you want foo to have the type Writer String Int you might try:
foo = tell "hello" >> return (5*5)
a.k.a.
foo = do
tell "hello"
return (5*5)
Remember the 'return type' of a monad isn't somehow 'fixed' so you're
stuck for it. Each statement can return a different type (and all the
values are ignore unless you bind them with a "x <-"). The 'return type'
of the entire expression is simply whatever is returned by the last
statement.
Hope that helps,
Jules
More information about the Haskell-Cafe
mailing list