Я новичок в 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"
Похоже, что состояние в pipeitState должно быть того же типа, что и тип входа канала. По крайней мере, это то, что я понял из сообщения об ошибке:
$ 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
Как это можно сделать с помощью трубопроводов? Я хочу читать строки из файла и добавлять номер строки к каждой строке.