我是一名 Haskell 初学者,试图将我的头绕在导管库上。
我试过这样的东西,但它没有编译:
import Data.Conduit
import Data.Conduit.Binary as CB
import Data.ByteString.Char8 as BS
numberLine :: Monad m => Conduit BS.ByteString m BS.ByteString
numberLine = conduitState 0 push close
where
push lno input = return $ StateProducing (lno + 1) [BS.pack (show lno ++ BS.unpack input)]
close state = return state
main = do
runResourceT $ CB.sourceFile "wp.txt" $= CB.lines $= numberLine $$ CB.sinkFile "test.txt"
看来,conduitState 中的状态必须与管道的输入类型属于同一类型。或者至少这是我从错误消息中理解的:
$ ghc --make exp.hs
[1 of 1] Compiling Main ( exp.hs, exp.o )
exp.hs:8:27:
Could not deduce (Num [ByteString]) arising from the literal `0'
from the context (Monad m)
bound by the type signature for
numberLine :: Monad m => Conduit ByteString m ByteString
at exp.hs:(8,1)-(11,30)
Possible fix:
add (Num [ByteString]) to the context of
the type signature for
numberLine :: Monad m => Conduit ByteString m ByteString
or add an instance declaration for (Num [ByteString])
In the first argument of `conduitState', namely `0'
In the expression: conduitState 0 push close
In an equation for `numberLine':
numberLine
= conduitState 0 push close
where
push lno input
= return
$ StateProducing (lno + 1) [pack (show lno ++ unpack input)]
close state = return state
如何使用管道来做到这一点?我想从文件中读取行并将行号附加到每一行。