在Haskell中使用带有Conduit的Writer monad

时间:2016-07-12 23:57:02

标签: haskell monads conduit

作为学习Haskell,Conduit和Monads的练习,我想创建一个告诉输入值并传递它的管道。

代码很简单,但我收到的编译错误对我来说仍然很神秘:

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

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

错误:

 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 }

1 个答案:

答案 0 :(得分:3)

这对我有用:

{-# 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

注意我将名称从log更改为doit,以避免名称与Prelude.log发生冲突。

<强>更新

如果您从:

开头
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

你会得到两个错误:

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

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

由于doit是顶级功能,因此经验会告诉您 或许单态性限制在这里起作用。 确实,在添加之后:

{-# LANGUAGE NoMonomorphismRestriction #-}

你只收到一个错误:

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

添加FlexibleContexts后,代码会编译。

现在您可以询问doit的类型:

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