How do you save a file using Conduit?

落花浮王杯 提交于 2019-12-07 23:01:48

问题


How do you save a file using conduit's library? I looked through conduit's tutorial but can't seem to find anything, here is my use case:

main :: IO ()
main = do
  xxs  <- lines <$> (readFile filePath)
  sourceList xxs =$ pipe $$ saveFile

pipe :: Monad m => Conduit String m String
pipe = undefined

So there's two question here:

  1. Does it make sense to use lines to convert a string into a list of strings and then feeding it to sourceList?

  2. How should I implement the saveFile function so that when the strings xxs are fully processed, I can write it to disk?


回答1:


A small minimal example of what you are trying to do using the conduit library:

#!/usr/bin/env stack
{- stack
     --resolver lts-6.7
     --install-ghc
     runghc
     --package conduit-extra
     --package resourcet
     --package conduit
 -}

import Data.Conduit.Binary (sinkFile, sourceFile)
import Control.Monad.Trans.Resource
import Data.Conduit (($$), await, Conduit, (=$), yield)
import Data.Monoid ((<>))
import Control.Monad.IO.Class

myConduit = do
  str <- await
  case str of
    Just x -> do
              liftIO $ print "some processing"
              yield x
              myConduit
    Nothing -> return ()


saveFile :: FilePath -> FilePath -> IO ()
saveFile f1 f2 = runResourceT $ sourceFile f1 $$ myConduit =$ sinkFile f2

main :: IO ()                 
main = saveFile "test.txt" "atest.txt"

How should I implement the saveFile function so that when the strings xxs are fully processed, I can write it to disk?

You implement that in your myConduit function. Note that in your example you are using readFile function call which will read the file lazily. Conduit provides it's own abstraction for reading and writing files, you should use that.



来源:https://stackoverflow.com/questions/38863820/how-do-you-save-a-file-using-conduit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!