yonutix
yonutix

Reputation: 2429

Writer monad operator definition issue

I want to define >>= operator for a Write monad. I tried something like that but it doesen't work (Does not compile). May I get some help? Thanks

newtype Writer a = Writer { runWriter :: (a, [String]) }

instance Monad Writer where
    return = Writer

    Writer m >>= f = Writer $ \r ->
        (runWriter (f m) r)

I get this:

Couldn't match type ‘a’ with ‘(a, [String])’

I get this error at return line, but also >>= is not defined well, I'm trying to get it right.

Upvotes: 0

Views: 72

Answers (2)

nponeccop
nponeccop

Reputation: 13677

Writer constructor expects a tuple of a and what is already written. return writes nothing so

return a = Writer (a, [])

Upvotes: 2

MathematicalOrchid
MathematicalOrchid

Reputation: 62808

First: The type signature for return should be x -> Writer x. However, the type signature of Writer is currently (x, [String]) -> Writer x, which is wrong.

Second: Writer m >>= f = Writer $ \r -> ... But the argument to Writer isn't declared to have a function type. So that doesn't look like it's going to work. Also, you're calling f :: x -> Writer y with an argument of type (x, [String]), which can't work.

In short, the whole thing as it stands just isn't right. So that's why it won't compile; not sure how many hints you're after on how to fix it.

Upvotes: 5

Related Questions