And Pos
And Pos

Reputation: 147

Using the Writer monad with Conduit in Haskell

As an exercise for learning Haskell, Conduit and Monads, I want to create a conduit that tells the input value and passes it through.

Code is pretty simple, but I'm getting compilation errors that are still cryptic for me:

 log =
    await >>= \case
      Nothing -> return ()
      Just value -> do
        tell [value]
        yield value

 runWriter $ CL.sourceList ["a", "b"] $= log $$ CL.consume

And the error:

 No instance for (MonadWriter [o0] m0) arising from a use of ‘tell’
 The type variables ‘m0’, ‘o0’ are ambiguous
 Relevant bindings include
   value :: o0
     (bound at /home/vagrant/workspace/dup/app/Main.hs:241:10)
   logg :: ConduitM o0 o0 m0 ()
     (bound at /home/vagrant/workspace/dup/app/Main.hs:238:1)
 Note: there are several potential instances:
   instance MonadWriter w m => MonadWriter w (ConduitM i o m)
     -- Defined in ‘conduit-1.2.6.4:Data.Conduit.Internal.Conduit’
   instance MonadWriter w m =>
            MonadWriter
              w (conduit-1.2.6.4:Data.Conduit.Internal.Pipe.Pipe l i o u m)
     -- Defined in ‘conduit-1.2.6.4:Data.Conduit.Internal.Pipe’
   instance [safe] MonadWriter w m =>
                   MonadWriter w  (Control.Monad.Trans.Resource.Internal.ResourceT m)
     -- Defined in ‘Control.Monad.Trans.Resource.Internal’
   ...plus 11 others
 In a stmt of a 'do' block: tell [value]
 In the expression:
  do { tell [value];
       yield value }
 In a case alternative:
    Just value
      -> do { tell [value];
              yield value }

Upvotes: 2

Views: 174

Answers (1)

ErikR
ErikR

Reputation: 52029

Here's what works for me:

{-# LANGUAGE FlexibleContexts #-}

import Data.Conduit
import Control.Monad.Writer
import qualified Data.Conduit.List as CL

doit :: MonadWriter [i] m => Conduit i m i
doit = do
  x <- await
  case x of
    Nothing -> return ()
    Just v  -> do tell [v]; yield v; doit

foo = runWriter $ CL.sourceList ["a", "b", "c"] =$= doit $$ CL.consume

Note I changed the name from log to doit to avoid the name clash with Prelude.log.

Update

If you start with:

import Data.Conduit
import Control.Monad.Writer
import qualified Data.Conduit.List as CL

doit = do
  x <- await
  case x of
    Nothing -> return ()
    Just v -> do tell [v]; yield v; doit

you will get two errors:

No instance for (Monad m0) arising from a use of ‘await’
...

No instance for (MonadWriter [o0] m0) arising from a use of ‘tell’
...

Since doit is a top-level function, experience will tell you that perhaps the monomorphism restriction is at work here. Indeed, after adding:

{-# LANGUAGE NoMonomorphismRestriction #-}

you only get one error:

Non type-variable argument in the constraint: MonadWriter [o] m
(Use FlexibleContexts to permit this)
...

And after adding FlexibleContexts, the code compiles.

Now you can interrogate the type of doit:

ghci> :t doit
doit :: MonadWriter [o] m => ConduitM o o m ()

Upvotes: 3

Related Questions