Defining a reference for a makeshift transformer

I defined my own version of WriterT along with the function to deploy it:

newtype WT w m a = WT (m a, w)

unWT :: (Monoid w, Monad m) => WT w m a -> (m a, w)
unWT (WT cmaw) = cmaw

Now I'm trying to define a monad (WT w m)without success:

instance (Monoid w, Monad m) => Monad (WT w m) where
  return x = WT (return x, mempty)
  wtwma >>= fawtwmb = WT $ let (ma, w1) = unWT wtwma
                               (mb, w2) = unWT $ do a <- ma
                                                    fawtwmb a
                           in (mb, mappend w1 w2)

The error is in the do-expression, at the point where I am trying to extract afrom ma:

Expected type: WT w m a, Actual type: m a

I tried several options, always with the same result. I can not determine bindfor this monad.

My main question is: if the monad is inside the pair, how can I extract its value?

+4
source share
1 answer

Imagine the following calculation:

tellLine :: WT String IO ()
tellLine = do
    input <- WT (getLine, "")
    WT (return (), input)

impossible :: String
impossible = snd (unWT tellLine)

"", , impossible - , . IO; impossible String, . , w, .

- w, , - . , .

return x >>= f = f x

, " " , , . w, , .

w mempty. - .

m >>= return = m

, m mempty w, .

WT . WriterT, m (a,w), .

+6

All Articles